Summary : Think of a tuple as a snippet of immutable data. They are typically used to represent short sets of data that can either be set as global immutable variables to be used further downstream. However, they are not used to create complex data structures like lists or large datasets like sets.
- What are Tuples
- Access Tuple Elements
- Modify Tuple Elements
- Advantages of Tuples over Lists
- Tuple Methods
- Other built-in functions
What are Tuples
Think of a tuple as a snippet of immutable data. For example, here is a snippet that represents Brad Pitt.
person_1 = ("Brad Pitt", 55, "Los Angeles") person_2 = ("Angelina Jolie", 45, "Beverly Hills")
Creating a tuple with only 1 element is a bit tricky. You would have to use an extra comma. For example, this would be a string, not a tuple
tuple_1 = ("Brad Pitt") type(tuple_1)
However, this would be a tuple.
tuple_2 = ("Brad Pitt",) type(tuple_2)
The reason why this happens is because, parenthesis can be used to define precedence. So, to define a tuple with a single element, you have to use an additional comma. You can even define a tuple without the paranthesis.
person_1 = "Brad Pitt", 55 , "Los Angeles" person_1
('Brad Pitt', 55, 'Los Angeles')
You can even convert a List to a Tuple
person_list = ["Brad Pitt",55,"Los Angeles"] person_tuple = tuple(person_list) person_tuple
('Brad Pitt', 55, 'Los Angeles')
Access Tuple Elements
Just like a List, you can access members of the tuple using indices.
name_1 = person_1 name_1
Or using slices
('Brad Pitt', 55)
Or using negative indexing
Modify Tuple Elements
However, unlike a list, you cannot change it’s values. For example, this is an illegal operation.. Remember, tuples are immutable
person_1 = "Sean Penn" --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-26-654366a6f906> in <module> ----> 1 person_1 = "Sean Penn" TypeError: 'tuple' object does not support item assignment
However, if the elements of a tuple are mutable, they can be changed . For example, these lists themselves cannot be changed, but their elements can be.
cast = (["Brad Pitt",55,"Los Angeles"],["Angelina Jolie",45,"Beverly Hills"])
cast = "Tom Cruise" cast = 56 cast
(['Tom Cruise', 56, 'Los Angeles'], ['Angelina Jolie', 45, 'Beverly Hills'])
Advantages of Tuples over Lists
- Tuples are immutable. So, iterating over a tuple in a loop is much more efficient than lists.
- Tuples are write-protected. So, python guarantees that any code that uses this tuple will not be able to change it. So, you can use it for holding data that is constant and global in nature
Since tuples are immutable, there are very few in-built methods to it.
count ( ) returns the number of occurrences of an elements in the tuple.
ages = (4,5,7,3,4,7,8,5,8,5) ages.count(7)
index ( ) returns the first index of the occurrence of an element in the tuple
ages = (4,5,7,3,4,7,8,5,8,5) ages.index(7)
Other built-in functions
Other built-in functions in Python that works on other iterables (like lists) work on tuples as well. For example,
- len ( )
- min ( )
- max ( )
- del ( )
- sum ( )
- filter ( )
len ( )Length of a Tuple.
vowels = ('a','e','i','o','u') len(vowels)
min & max
Find out the maximum and minimum values of a tuple . In the following example, alphabetic sorting is done to get the min or max.
android_versions = ( "Gingerbread","Honeycomb","Icecream Sandwhich","Cupcake", "Donut", "Eclair", "Froyo", "Jellybean", "Kitkat", "Lollypop","Marshmallow", "Nougat","Oreo","Pie") max(android_versions)
Similarly, use the min ( ) function to get the minimum value in the tuple.
del ( ) deletes a tuple.
sum ( ) adds up all the numbers in the tuple
ages = (4,5,7,3,4,7,8,5,8,5) sum(ages)
filter ( ) also works on tuple.
ages = (4,5,7,3,4,7,8,5,8,5) # Primary schools admist students from 5 to 11 def primary_schools ( age ) : if 11 >= age >= 5 : return True else : return False primary_school_age = filter(primary_schools, ages) for age in primary_school_age : print ( age )
5 7 7 8 5 8 5