How to select nth element in a list with python ?

Published: September 03, 2021

Tags: Python; List;

DMCA.com Protection Status

Examples of how to select nth element in a list with python:

Create a list

Let's first create a list with python:

mylist = ['A', 'B', 'C', 'D', 'E', 'F']

Note that a list is 0 based indexing.

index element
0 A
1 B
2 C
3 D
4 E
5 F

Check the following link to learn more about different data structures in python.

Select the first element of a list

To select the first element of a list

mylist[0]

returns here

'A'

Select the last element of a list

To select the last element of a list

mylist[-1]

returns here

'F'

Select nth element of a list

To select nth element of a list

mylist[4]

returns here

'E'

However

mylist[6]

will returns the following error message

IndexError: list index out of range

since the list contains only 6 element.

To avoid that

index = 6
if index < len(mylist):
    print(mylist[index])
else:
    print('Warning: list index out of range')

or

try:
    mylist[index]
except:
    pass

Find index of a given element

Note to find the index of a given element

mylist.index('D')

returns

3

Note: To check if an element is in a list:

'D' in mylist

returns

True

while

'G' in mylist

returns

False

Loop through a list and print element with associated index

To loop through a list and print element with associated index, a solution is to use enumerate()

for i,e in enumerate(mylist):
        print(i,e)

returns here

0 A
1 B
2 C
3 D
4 E
5 F

References