Python Program to Print the Elements of an Array Present on Even Positions

Python Program to Print the Elements of an Array Present on Even Positions

Arrays (or lists in Python) are widely used data structures that store collections of elements. A common task is to extract and work with elements based on their positions within the array. In this blog post, we'll discuss how to print elements of an array located at even positions.

Problem Statement
Given an array, print the elements that are present at even positions. Remember that in programming, array indexing typically starts from 0, so the positions to consider are 0, 2, 4, etc.
For example, if the array is [10, 20, 30, 40, 50], the output should be 10, 30, 50 since these are the elements at even indices (0, 2, 4).

Approach
  1. Loop through the array using a for loop with an index.
  2. Use the modulo operator (%) to check if the index is even.
  3. If the index is even, print the corresponding element.
Python Code
Here's a Python program that prints the elements of an array located at even positions:
Copy code

# Python program to print elements of an array at even positions
# Initialize the array
array = [10, 20, 30, 40, 50, 60]
# Print a message indicating the elements at even positions
print("Elements at even positions:")
# Iterate through the array using the index
for i in range(len(array)):
    # Check if the position is even
    if i % 2 == 0:
        print(array[i], end=' ')

Output
Copy code
Elements at even positions:
10 30 50

Explanation of the Code
  • Initialization: The array is initialized with some values.
  • Iteration with Index: The for loop iterates through each array index using range(len(array)).
  • Checking Even Index: Inside the loop, the if i % 2 == 0 condition checks whether the index is even. If true, the corresponding element is printed.

This is the screenshot of the Jupyter Notebook of the Above Program

Conclusion
Extracting elements based on their positions is a basic but crucial operation in programming. Knowing how to manipulate arrays and retrieve elements from specific positions is an important skill for any developer. Whether using loops, slicing, or other Pythonic techniques, these methods offer efficient ways to access data stored in arrays.
Understanding these basic array manipulations will help you handle more complex data processing tasks in Python.

Comments