Skip to main content

How to Get Even or Odd Index Elements from a List in Python

This guide explores different methods to extract elements from a list in Python based on whether their index is even or odd. We'll cover list slicing, for loops, and using the itertools.islice() function, providing efficient and readable solutions.

List slicing provides the most concise and Pythonic way to get elements at even or odd indices.

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Get all elements with an even index
even = my_list[::2]
print(even) # Output: [0, 2, 4, 6, 8, 10]

# Get all elements with an odd index
odd = my_list[1::2]
print(odd) # Output: [1, 3, 5, 7, 9]
  • my_list[::2]: Gets all elements with even indices. The slice starts at the beginning (index 0), goes to the end, and takes every second element (step of 2).
  • my_list[1::2]: Gets all elements with odd indices. The slice starts at index 1, goes to the end, and takes every second element.

Getting Every N-th Element

Getting every n-th Element starting with the nth Element

You can use the general form my_list[n-1::n] to return every nth element of the list.

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = 2
every_second = my_list[n - 1::n]
print(every_second) # Output: [1, 3, 5, 7, 9]

Getting every n-th Element starting from a given Index

You can also specify the starting index:

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
every_second = my_list[2::2]
print(every_second) # Output: [2, 4, 6, 8, 10]

Getting Even or Odd Index Elements with a for Loop

While slicing is generally preferred for its conciseness, you can use a for loop and the modulo operator (%) for more complex logic:

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even = []
odd = []

for index, item in enumerate(my_list):
if index % 2 == 0:
even.append(item)
else:
odd.append(item)

print(even) # Output: [0, 2, 4, 6, 8, 10]
print(odd) # Output: [1, 3, 5, 7, 9]
  • enumerate() provides both the index and value of each item.
  • index % 2 == 0 checks if the index is even (remainder of division by 2 is 0).

Getting Even or Odd Index Elements with islice()

The itertools.islice() function provides an iterator-based approach to slicing, which can be useful for very large lists:

from itertools import islice

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even = list(islice(my_list, 0, len(my_list), 2))
print(even) # Output: [0, 2, 4, 6, 8, 10]

odd = list(islice(my_list, 1, len(my_list), 2))
print(odd) # Output: [1, 3, 5, 7, 9]
  • islice(my_list, start, stop, step) creates an iterator that yields elements from my_list according to the slice parameters. It's like list slicing, but works with iterators and avoids creating intermediate lists.