Get every other element in a list in Python

avatar

Borislav Hadzhiev

Last updated: Aug 17, 2022

banner

Photo from Unsplash

Get every other element in a list in Python #

Use list slicing to get every other element in a list, e.g. new_list = my_list[::2]. The new list will contain every other element of the original list.

main.py
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # ✅ get every other element in list (starting at index 0) new_list = my_list[::2] print(new_list) # 👉️ [0, 2, 4, 6, 8, 10] # ✅ get every other element in list (starting at index 1) new_list = my_list[1::2] print(new_list) # 👉️ [1, 3, 5, 7, 9]

We used list slicing to get every other element in a list.

The syntax for list slicing is my_list[start:stop:step].

The start index is inclusive and the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

The slice my_list[::2] gets every other element in the list, starting at index 0.

main.py
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_list = my_list[::2] print(new_list) # 👉️ [0, 2, 4, 6, 8, 10]

The start and end indexes are omitted, so the slice starts at index 0 and goes to the end of the list.

The step value is set to 2, so the slice selects every second element.

You can use the same approach if you need to get every other element in a list starting at index 1 (or any other index).

main.py
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_list = my_list[1::2] print(new_list) # 👉️ [1, 3, 5, 7, 9]

Instead of starting at index 0, the slice starts at index 1 and selects every other element.

The stop index is omitted, so the slice goes to the end of the list.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.