Published: Aug. 11, 2019 by lukemakin |  estimated reading time: 4 minutes
The 3rd part of series on Python data structures is here. After looking into lists and dictionaries, it's time to cover tuples which are immutable and ordered, as well as methods associated to them. Immutable is the keyword here - you can't modify once defiened  tuple. Without further due, let's get started.

Our tuple consists of dc comics superheroes:

dc_heroes = ('Superman', 'Batman', 'Green Arrow', 'Wonder Woman', 'Flash', 'Aquaman')

Let's say we want to find out about the position of the Flash - we can use the index() method:


dc_heroes.index("Flash")

'''
Output:
4
'''

Similarly if we want to access certain position, but this time without the use of any method but just by referring to the index number in the brackets:


dc_heroes[4]

'''
Output:
Flash
'''

Moving forward - let's print out the content of the enitre tuple:


for hero in dc_heroes:
print(hero)

Output:
'''
Superman
Batman
Green Arrow
Wonder Woman
Flash
Aquaman
'''

Since tuples are immutable, we can't modify their structure in anyway. If there's a need to perform an operation, you can modify the list by creating a new one (new variable with different location in the memory). Here's an example of creating a new tuple with items that have even number indexes:


dc_new = tuple([x for i,x in enumerate(dc_heroes) if i%2==0])
print(dc_new)

'''
Output:
('Superman', 'Green Arrow', 'Flash')
'''

Now that we have a new tuple with selected items we can check if particular item is inside the list:


if "Wonder Woman" in dc_new:
print("yeaaah")
else:
print("buuu")

'''
Output:
buuu
'''

Finally we can check the difference in size of both tuples:


len_diff = len(dc_heroes) - len(dc_new)
print(len_diff)

'''
Output:
3
'''

That is pretty much it. As you can see, tuples range of methods is much smaller than lists and dictionaries because of its immutability.

It makes them relatively easy to learn (especially if you already know lists) and convenient in cases where your data structure has to be fixed and ordered. In the next one we''ll cover set's and frozen sets.
 



Extras
To view additional content login or create a free account
Categories:
Share your thoughts

No comments yet...

Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019 pyplane.com