Get every other element in a List in Python

This tutorial will discuss about unique ways to get every other element in a list in Python.

Table Of Contents

Method 1: Using Slicing

We can use the slicing to select every 2nd element from list i.e. every other element from list.

listOfNumbers[1 : : 2]

It will return a sublist containing every another element from the list. Basically it selects every 2nd element from list i.e. from index position 1 till the end of list, and with a step size 2.

Let’s see the complete example,

listOfNumbers = [11, 22, 33, 44, 55, 66, 77, 88, 99, 109]

# Get every other element from List

subList = listOfNumbers[1 : : 2]

print (subList)

Output

[22, 44, 66, 88, 109]

Method 2: Using itertools

The itertools module in Python, provides a function islice(), to get some specific elements from list based on slicing. So, to select every 2nd element from list i.e. every other element, pass the following arguments in islice()

list(itertools.islice(listOfNumbers, 1, None, 2))

It will return a sublist containing every 2nd element from the list. Basically, the islice() method returns an iterator pointing to every 2nd element from list, because we started the slicing from index position 1 till the end of list, and with a step size 2. In the end, we passed that iterator to the list() method, to get a list containing every other element of main list.

Let’s see the complete example,

import itertools

listOfNumbers = [11, 22, 33, 44, 55, 66, 77, 88, 99, 109]

# Get every other element from List
subList = list(itertools.islice(listOfNumbers, 1, None, 2))

print(subList)

Output

[22, 44, 66, 88, 109]

Summary

We learned about different ways to get every other element from a List in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top