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

Introduction

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

print(list_included)
print(dict_included)
print(tup_included)
print(string_included)

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.

Advertisement

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:

WordPress.com Logo

You are commenting using your WordPress.com 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

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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

%d bloggers like this: