Python language basics 43: find the position of an element in a collection
August 30, 2015 Leave a comment
Introduction
In the previous post we looked at how to remove elements from a collection in Python. We discussed the del keyword and the remove function. The del keyword works based on indexes whereas the remove function accepts the object to be removed.
In this post we’ll look at the index function which helps us locate an element in a collection.
Index
Consider the following cities list:
cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"]
If you want to find the position of say Paris you can use the index function directly on the collection. It returns the position as an integer:
paris_pos = cities.index("Paris")
‘paris_pos’ will be 3.
If the supplied object doesn’t exist you’ll get an exception which we’ll see how to handle later:
paris_pos = cities.index("paris")
ValueError: ‘paris’ is not in list
The index function can also accept a start and end index where to search:
paris_pos = cities.index("Paris", 4, 5)
The above code will throw an exception as there’s no ‘Paris’ in the referenced index range.
Read the next post here.
Read all Python-related posts on this blog here.