Python language basics 35: determine if an element is included in a collection


In the previous post we looked at how to return multiple values from a function in Python. We saw that this is fact was only possible through a trick where the trick was to use a collection of type Tuple. We went through an example with a simple function that returned 4 values in a tuple. We also discussed how to access individual elements in the tuple.

In this post we’ll see how to determine if a certain element is located in a collection.

The ‘in’ operator

We’ve looked at the following collection types in this series so far:

It’s easy to determine whether a certain element is found in any of these collections using the in operator. It can be applied to all the above mentioned collections:

my_list = [1, 3, 4, 5, 6]
my_dict = {"S": "Small", "M": "Medium", "L": "Large", "XL": "X-Large"}
my_tuple = (10, 13, 15, 17, 11)
name = "Elvis Presley"
list_included = 1 in my_list
dict_included = "S" in my_dict
tup_included = 11 in my_tuple
string_included = 'vi' in name


All boolean variables will resolve to True.

The opposite of the ‘in’ operator is quite simply not in:

my_list = [1, 3, 4, 5, 6]
list_included = 1 not in my_list

list_included will be False.

Read the next part 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: