Python language basics 43: find the position of an element in a collection


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.


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.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: