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.

Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT BEST PRACTICES WITH MICROSOFT STACK & ANGULAR

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: