Python language basics 35: determine if an element is included in a collection
August 2, 2015 Leave a comment
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:
- Lists
- Dictionaries
- Tuples in the previous post referenced above
- Strings which are really collections of characters
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.