Milandeep Bassi

Using Tuple Data Structures in Python Programming

4th, February, 2020


Tuples

To declare a tuple we use brackets instead of square brackets.

mytuple = (1, 2, 3, 4, 5)

Indexing in the tuples works exactly the same as the lists. The output of a tuple is always shown with brackets. 

Tuples are different from lists as once they're created they cannot be changed. This makes them an immutable data type. This means elements cannot be replaced, removed or added.

Tuples can contain mutable elements such as a list. These contents while inside the tuple can be changed. The only way to change a tuple is to reassign it with new data. 

Lists in comparison are more powerful and have many useful functions. However a tuple can be converted into a list and a list to tuple. But if all you need is the simple functionality of a tuple they can work faster. A tuple is more desirable if they have a fixed number of elements and are not going to be changed. 

mylist = list(mytuple)
mytuple = tuple(mylist)

By using a tuple you also get the benefit of assigning multiple variables at one time. 

a, b, c = 1, 2, 3
print (a, b, c)

>>>
1 2 3
>>>

a = 1
b = 3
a, b = b, a
print (a, b)

>>>
3 1
>>>