Python : Crash Course Part 6 – Tuples

Tuples in python act similar to that of a python list. In list we pass the elements within a square bracket, but in tuples it is parenthesis ( open & close brackets ). The other major difference between tuples and lists is that elements inside a list can be updated. To see how the elements can be updated refer to my previous blog post on lists. Tuples on the other hand cannot be updated. It’s more of a read only object once it is created. Fetching the data out of a tuple and a list will still remain the same. Having said that the indexing would act similar in a tuple and a list.

In [1]:tuple = (1,2,3)
In [2]:tuple[0]

Try assigning / updating an element in your tuple and let me know what error you get in the comments section below.

If you are not aware of what a for or while loop is, don’t worry about it much. Those are covered in the upcoming courses. What I wanted to show you is tuple unpacking using the for loop.

Lets say we have a list of tuples as shown below :

In [4]:x=[(1,2),(3,4),(5,6)]

We can unpack and print the elements using tuple unpacking with the help of a for loop :

In [5]:for (a,b) in x:
                     print (a)
                     print (b)

That’s how you unpack a tuple. the values in x in the form of a tuple ( a,b ) will be fed into a for loop. You can come back to this topic after you complete the for loop course in this series. You can however tend to skip this unpacking topic for now.