Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to print the elements of an array present on even position
When it is required to print the elements of a list that are present at even index/position, a loop can be used to iterate over the elements, and only check the even positions in the list by specifying the step size as 2 in the range function.
Below is a demonstration of the same −
Example
my_list = [31, 42, 13, 34, 85, 0, 99, 1, 3]
print("The list is :")
print(my_list)
print("The elements in even positions are : ")
for i in range(0, len(my_list), 2):
print(my_list[i])
Output
The list is : [31, 42, 13, 34, 85, 0, 99, 1, 3] The elements in even positions are : 31 13 85 99 3
Alternative Methods
Using List Slicing
You can also use list slicing with step size 2 to get elements at even positions ?
my_list = [31, 42, 13, 34, 85, 0, 99, 1, 3]
print("The list is :")
print(my_list)
print("The elements in even positions are : ")
even_elements = my_list[::2]
print(even_elements)
The list is : [31, 42, 13, 34, 85, 0, 99, 1, 3] The elements in even positions are : [31, 13, 85, 99, 3]
Using List Comprehension
List comprehension provides a concise way to create a new list with elements at even positions ?
my_list = [31, 42, 13, 34, 85, 0, 99, 1, 3]
print("The list is :")
print(my_list)
print("The elements in even positions are : ")
even_elements = [my_list[i] for i in range(0, len(my_list), 2)]
print(even_elements)
The list is : [31, 42, 13, 34, 85, 0, 99, 1, 3] The elements in even positions are : [31, 13, 85, 99, 3]
Explanation
A list is defined, and is displayed on the console.
The list is iterated over beginning from the first index element (index 0), and the step size is mentioned as 2 in the range method.
Those elements that are in even positions (indices 0, 2, 4, 6, 8) are displayed on the console.
List slicing
[::2]starts from index 0 and takes every second element.List comprehension creates a new list by iterating through even indices.
Conclusion
Use range(0, len(list), 2) for loop-based iteration, list[::2] for simple slicing, or list comprehension for functional programming approach. All methods extract elements at even positions (indices 0, 2, 4, etc.).
