Print elements at odd indices in a list


Print elements at odd indices in a list

In this tutorial, you are given a list, and you will learn how to iterate over the odd indices [1, 3, 5, 7, ...] of the list.

To print the elements at odd 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 1, and increments in steps of 2, until the length of the list. The range object returns a sequence of integers starting from 1, in steps of 2, the odd 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 odd indices of a given list mylist is shown in the following.

range(1, 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 odd numbered indices

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

Python Program

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

Output

berry
fig
kiwi

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(1, len(mylist), 2):
    print(mylist[i])

Output

8
16
24
32
40

References

Summary

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