Understanding tuples in python

This article is made for complete understanding of tuples in python including creating, accessing, packing, unpacking, looping, of tuples.

Introduction

Tuples are a kind of data structure in python that is well known for their immutable behavior. Lists in python as we know are mutable which makes tuples different from lists. But hold on, What are these mutable and immutable mean? let's find out in this article. This article is made for a complete understanding of tuples in python and their differences from the list.

Things you'll learn:

What are tuples in python?

A tuple can be defined as an ordered list of elements that can store data types including numbers, strings, boolean values, etc. The main difference between a tuple and a list is that tuples are immutable while lists are mutable, which means, you can modify the items inside a list anytime and anywhere in your program that cannot be done in a tuple. A tuple in python is created using paratheses ( ) unlike square brackets in the case of lists. 

numbers = (200, 300, 400, 500, 600)
print(numbers)

(200, 300, 400, 500, 600)

Advantages of Tuples 

  • Tuples are fixed once created, so it helps to avoid accidental modification
  • Tuples are pretty faster than lists since they cannot be manipulated
  • Tuples are indexable
  • Tuples can hold different data types at the same time, hence they are heterogeneous in nature.

Retrieving elements from a tuple

The elements inside a tuple can be accessed using the index of each element as same as lists. 

numbers = (200, 300, 400, 500, 600)
print(numbers[0])
print(numbers[1])
print(numbers[2])
print(numbers[3])
print(numbers[4])

 The elements inside the tuple is being accessed by using the name of the tuple followed by square brackets and the index. 

Now let's see what happens when you try to change the values inside a tuple.

numbers = (200, 300, 400, 500, 600)
numbers[0] = 250

print(numbers)

TypeError: 'tuple' object does not support item assignment

You'll encounter a type error if you try to assign values to a tuple since you can't directly modify a tuple with new values.

But to modify a tuple there are lots of possible ways, one is to create a new tuple with the same name as given below.

languages = ("COBOL", "FORTRAN", "Pascal")

# New languages
languages = ("Python", "Java", "JavaScript", "Swift")

print(languages)

output:

("Python", "Java", "JavaScript", "Swift")

Here the formal tuple containing some of the old programming languages is being overwritten by new languages. It will work fine since the overwriting of a variable in python is literally possible.

Modifying tuples using lists

There is one interesting way to modify a tuple which is by using a list. The method is that the tuple is first converted to a list and the list is being modified which is then converted to a tuple again. This method can be done during the runtime of the program.

languages = ("Python", "Java", "Kotlin", "C++")

# Converting tuple to a list
languages = list(languages)

# Modifying list
languages.append("JavaScript")
languages.remove("C++")

# Converting list back to tuple
languages = tuple(languages)

print(languages)

output:

('Python', 'Java', 'Kotlin', 'JavaScript')
 
Since a list is mutable, first we converted the languages tuple to a list using list keyword and then added and removed one programming language. Then the modified list is then converted back to the tuple using the tuple keyword and the result is being printed.

Packing and Unpacking of tuple

Assigning a tuple to a variable is simply known as the Packing of a tuple. What is Unpacking then? In python, there is an assignment feature for tuples that assigns the values of the right-hand side to the left-hand side which is known as Unpacking of a tuple. For better understanding let's take an example.

Consider the following code 

# Packing a tuple
profile = ("Alex", 20, "Programmer")

# Unpacking a tuple 
(name, age, profession) = profile

print("Name:",name)
print("Age:", age)
print("Profession:", profession)

output:
Name: Alex
Age: 20
Profession: Programmer

We created a variable profile by giving some details of a person inside a tuple, and in the next step, the tuple is unpacked to corresponding individual variables name, age, and profession given on the left-hand side. The corresponding values on the right-hand side are assigned to the left-hand side. This is known as the Unpacking of tuple.

Note that the number of variables on the left-hand side must be equal to the number of values in the tuple, else it will throw an unpacking error. 

But it is possible to unpack two or more values to a single variable in python by the concept of *args Keyword. *args keyword is used to pass optional arguments and it can hold as many arguments. Let's see an example

# Packing a tuple
profile = ("Alex", 20, "Programmer", "Java", "Python", "R")

# Unpacking a tuple 
(name, age, profession, *known_languages) = profile

print("Name:",name)
print("Age:", age)
print("Profession:", profession)
print("Known Languages:", known_languages)

output:
Name: Alex Age: 20 Profession: Programmer Known Languages: ['Java', 'Python', 'R']

Here the first, second, and third values of the tuple profile are assigned to the corresponding variables name, age, profession, and the remaining values are assigned to a new variable *known_languages. 

Looping through a tuple

Looping through a tuple is the same as looping through a list, you can use a for loop for this purpose.

profile = ("Alex", 20, "Programmer", "Java", "Python", "R")

for data in profile:
  print(data)

output:
Alex 20 Programmer Java Python R

Looping through the index of the tuple

You can also use index numbers to loop through a tuple using the len() and range() function as shown below,

profile = ("Alex", 20, "Programmer", "Java", "Python", "R")

for i in range(len(profile)):
  print(profile[i])

Loop using while

Looping using a while statement can be also done in tuples. First, start from 0 and loop through all the indexes until the length of the tuple. Don't forget to increase the index by one in each iteration when using a while loop.

profile = ("Alex", 20, "Programmer", "Java", "Python", "R")

= 0
while i < len(profile):
  print(profile[i])
  i = i+1