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
Program to find only even indexed elements from list in Python
In Python, we can extract elements at specific positions from a list. To find only even indexed elements (elements at positions 0, 2, 4, etc.), we can use list slicing techniques.
So, if the input is like nums = [5, 7, 6, 4, 6, 9, 3, 6, 2], then the output will be [5, 6, 6, 3, 2] (elements at indices 0, 2, 4, 6, 8).
Understanding Even vs Odd Indices
Let's first clarify the index positions in our example list ?
nums = [5, 7, 6, 4, 6, 9, 3, 6, 2]
# Display elements with their indices
for i, value in enumerate(nums):
index_type = "even" if i % 2 == 0 else "odd"
print(f"Index {i}: {value} ({index_type})")
Index 0: 5 (even) Index 1: 7 (odd) Index 2: 6 (even) Index 3: 4 (odd) Index 4: 6 (even) Index 5: 9 (odd) Index 6: 3 (even) Index 7: 6 (odd) Index 8: 2 (even)
Method 1: Using List Slicing
The most efficient approach uses Python's slicing syntax [start:end:step]. To get even indexed elements, start from 0 and step by 2 ?
def get_even_indexed(nums):
return nums[::2] # Start from 0, go to end, step by 2
nums = [5, 7, 6, 4, 6, 9, 3, 6, 2]
result = get_even_indexed(nums)
print("Original list:", nums)
print("Even indexed elements:", result)
Original list: [5, 7, 6, 4, 6, 9, 3, 6, 2] Even indexed elements: [5, 6, 6, 3, 2]
Method 2: Using List Comprehension
We can also use list comprehension with enumerate to filter even indexed elements ?
def get_even_indexed_comprehension(nums):
return [value for i, value in enumerate(nums) if i % 2 == 0]
nums = [5, 7, 6, 4, 6, 9, 3, 6, 2]
result = get_even_indexed_comprehension(nums)
print("Even indexed elements:", result)
Even indexed elements: [5, 6, 6, 3, 2]
Method 3: Using a Loop
A traditional approach using a for loop to collect even indexed elements ?
def get_even_indexed_loop(nums):
result = []
for i in range(0, len(nums), 2): # Start at 0, step by 2
result.append(nums[i])
return result
nums = [5, 7, 6, 4, 6, 9, 3, 6, 2]
result = get_even_indexed_loop(nums)
print("Even indexed elements:", result)
Even indexed elements: [5, 6, 6, 3, 2]
Comparison
| Method | Syntax | Performance | Readability |
|---|---|---|---|
| List Slicing | nums[::2] |
Fastest | Very High |
| List Comprehension | [v for i,v in enumerate(nums) if i%2==0] |
Medium | High |
| Loop | range(0, len(nums), 2) |
Slowest | High |
Conclusion
List slicing with [::2] is the most efficient and Pythonic way to extract even indexed elements. Use list comprehension when you need more complex filtering conditions, and traditional loops for educational purposes or when building results step by step.
