How to print elements at even indices in a list

Print elements at even indices in a list

In this tutorial, you are given a list, and you will learn how to iterate over the even indices [0, 2, 4, 6, …] of the list.

To print the elements at even indices in a given list in Python, you can use a For loop with range() built-in function.

Take a range object that starts at 0, and increments in steps of 2, until the length of the list. The range object returns a sequence of integers starting from 0, in steps of 2, the even numbered indices we require. Use a For loop statement to iterate over these indices, and print the elements.

The range object to iterate over the even indices of a given list mylist is shown in the following.

range(0, len(mylist), 2)

We have used len() built-in function, to get the number of elements in the list.

Examples

1. Print the elements of a list which are at even numbered indices

In the following program, we take a list of strings, and print the elements at the even numbered indices starting from zero.

Python Program

mylist = ['apple', 'berry', 'cherry', 'fig', 'mango', 'kiwi']
for i in range(0, len(mylist), 2):
    print(mylist[i])
Run Code Copy

Output

apple
cherry
mango

2. Print the even indexed elements of a numeric list

In the following program, we take a list of numbers, and print the elements at the even numbered indices.

Python Program

mylist = [4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
for i in range(0, len(mylist), 2):
    print(mylist[i])
Run Code Copy

Output

4
12
20
28
36

References

Summary

In this tutorial of Python List Operations, we learned how to iterate over and print the elements with even numbered index in a list, using a range object and For loop.

Code copied to clipboard successfully 👍