Explain Tuples in Python 3

When we deal with data collection, there are times when we need to ensure that we can’t change the order of the items once we’ve set them up. For example, when getting information from a database in Python, we can think of each table record as a fixed and unmodifiable list of items because we don’t want to change the order afterward. Tuples in Python serve this purpose, providing a built-in data type to store data in this unchangeable format.

After completing this Python tutorial, you’ll have learned:

  1. How to work with tuples in Python
  2. The difference between tuples and lists in Python
  3. The basic uses of tuples

In this tutorial, we assume you have a foundational understanding of Python, which includes knowledge of variables, data types, and basic data structures.

What Are Tuples in Python?

A tuple is a way to group different objects in Python. It consists of objects separated by commas and enclosed in parentheses. Tuples are immutable, meaning their contents cannot be changed once created. They help represent fixed collections of items.

Here are some examples of tuples in Python

  1. An empty tuple: ()
  2. A tuple with three numeric objects: (1.1, 9.0, 11)
  3. A tuple with four string objects: (‘cake’, ‘wafers’)
  4. A tuple with a string, an integer, and a Boolean object: (’11’, 112, false)

In addition to individual objects, you can also include other objects like lists and tuples within a tuple, like this:


data_tuple = (1, ["banana", "mango", 2], (3, 4, 5), 6.1)

The code you’ve described creates a tuple with a mix of different data types, including an integer, string, a list, a tuple, and a float number. You can retrieve the entire tuple and its data type using the following code.


data_tuple = (1, ["banana", "mango", 2], (3, 4, 5), 6.1)
print(data_tuple)
print(type(data_tuple))

When you run this code, it will print the entire tuple and its data type, showing something like:


(1, ["banana", "mango", 2], (3, 4, 5), 6.1)
<class 'tuple'>

How can we declare a single-value tuple?

The solution is simple. Just put an extra comma before the closing parenthesis, like this: (‘A’,). This extra comma indicates that the parentheses contain a single-value tuple, not being used to prioritize a mathematical operation.

Indexing and Slicing a Tuple

As I mentioned before, since a tuple is a sequence of items, we can get to these items using indexing. Like strings, the first element has an index of 0, the second has an index of 1, and so forth. Let’s give indexing a tuple a try:


data_tuple = (1, ["banana", "mango", 2], (3, 4, 5), 6.1)
print('The first element of data tuple:', data_tuple[0])
print('The last element of data tuple:', data_tuple[-1])
print('The data type of the second element of data tuple:', type(data_tuple[1]))

Output

The first element of the data tuple: 1
The last element of the data tuple: 6.1
The data type of the second element of the data tuple: <class ‘list’>

In the code above, the first and second statements give us the values of the first and last elements of the tuple. The final statement displays the data type of the second element in the tuple; in this case, it’s a list object.

Additionally, the below code demonstrates how to fetch the second element of the inner tuple, located at index 2.


data_tuple = (1, ["banana", "mango", 2], (3, 4, 5), 6.1)
print("in data tuple their element of index 1 in second element :",data_tuple[2][1])

Output

In the data tuple, their element of index 1 in the second element: 4

This implies that we can retrieve an element stored in an inner tuple (a tuple stored inside another tuple) by performing a sequence of indexing operations.

Slicing a tuple is as straightforward as slicing a Python string or a list, following the same rules. To obtain a range of elements within a tuple, we can indicate a range of indices, specifying both the starting point (inclusive) and the ending point (exclusive) of the desired range.

Now, let’s explore a few examples.


number_tuple = 1,2,3,4,5,6
print(number_tuple[:3])
print(number_tuple[4:])
print(number_tuple[-3:])
print(number_tuple[2:5])

Output

(1, 2, 3)
(5, 6)
(4, 5, 6)
(3, 4, 5)

The initial line of the code defines a tuple containing integer values. While it’s not typical, it’s another method of declaring a tuple by listing objects separated by commas without using parentheses. The following statements then print out various slices of the tuple, as illustrated.

To combine two or more tuples, we can utilize the + sign, similar to how it’s used with strings. For instance, the code below merges two tuples:


tuple_data1 = (3, 5)
tuple_data2 = (6, 7)
print(tuple_data1 + tuple_data2)

Output

(3, 5, 6, 7)

Furthermore, multiplying a tuple by an integer generates a tuple that consists of the original tuple repeated that specified number of times. Let’s give it a try:

mydata_tuple = (1, 2, 3, 5)
print(mydata_tuple * 2)

Output
(1, 2, 3, 5, 1, 2, 3, 5)

Zipping Tuples

The zip() method combines elements from multiple sequences and creates an iterable object. To understand how to zip tuples, let’s explore the following example:

Suppose we have three tuples with personal details for four customers. Our goal is to create a single tuple containing the relevant data for each customer, such as their first name, last name, and age, in the form of separate tuples:


f_name = ('Virat', 'M.S.', 'Rohit')
l_name = ('Kohli', 'Dhoni', 'Sharma')
ages = (35, 42, 36)
zipped_data = zip(f_name, l_name,ages)
print(zipped_data)

Output

zip object at 0x7f64d467a2c0>

In the code, we’ve defined three sets of information: first names, last names, and ages. Now, a method called zip() combines these sets into a special object called a “zip object.” This object is like a package that holds the information together.

But we need to do something to use or see the information inside this package. We can either turn it into a list or a tuple. It’s like unpacking the contents of the package so we can easily work with them.

So, in simpler terms, think of it like putting items in a bag. The zip() method puts our f_name, l_name, and ages into a special bag. To see what’s inside, we need to either turn that bag into a list or a tuple. It’s just a way to organize and access our data.


f_name = ('Virat', 'M.S.', 'Rohit')
l_name = ('Kohli', 'Dhoni', 'Sharma')
ages = (35, 42, 36)
zipped_data = zip(f_name, l_name,ages)
cricket_team = tuple(zipped_data)
print(cricket_team)

Output

((‘Virat’, ‘Kohli’, 35), (‘M.S.’, ‘Dhoni’, 42), (‘Rohit’, ‘Sharma’, 36))

The “cricket_team” tuple is like a big container that holds four smaller containers inside. Each of these smaller containers represents information about a different customer. So, in simpler terms, the “cricket_team” tuple is a collection that stores details about three cricketers, and each cricketer’s information is kept in one of those smaller containers.

Unpacking Tuples

When we unpack a tuple, we remove the elements from it and give them names as variables. Let’s give it a shot:

Imagine you have a tuple with some information packed inside. Unpacking is like opening that package and assigning names to each piece of information. It helps us work with the data more easily.


f_name = ('Virat', 'M.S.', 'Rohit')
l_name = ('Kohli', 'Dhoni', 'Sharma')
ages = (35, 42, 36)
zipped_data = zip(f_name, l_name,ages)
cricket_team = tuple(zipped_data)
first_name, last_name, age = cricket_team[2]
print(first_name, last_name, ',', age, 'years old')

Output

Rohit Sharma, 36 years old
In the given code, we are grabbing the information stored at position 2 inside the “cricket_team” tuple. This information includes a cricketer’s first name, last name, and age. After getting this bundle of data, we are assigning each piece of information to specific variables named “first_name,” “last_name,” and “age.” So, in simpler terms, we’re taking out details about a cricketer from the tuple and giving them easy-to-use names.

Usage of Tuples in Python

This section will discuss exciting ways of using tuples in practice. Let’s explore them.

Tuple Element Swapping

Imagine you have two boxes labeled ‘a’ and the ‘b’, each with a number inside. Now, you want to switch the numbers between the boxes. Tuples can help you do this easily.

Here’s how it works

  1. Look at the numbers in both boxes (let’s say ‘a’ has 5 and ‘b’ has 10).
  2. With tuples, you can magically switch these numbers without needing a temporary box.

a = 19
b = 91
print('Before swapping Data:')
print(f'a = {a}, b = {b}')
(a, b) = (b, a)
print('After swapping Data:')
print(f'a = {a}, b = {b}')

Output

Before swapping Data:
a = 19, b = 91
After swapping Data:
a = 91, b = 19

The value of b is assigned to the a variable, and the a value is simultaneously assigned to the b. It’s a more Pythonic way to swap values.

Conclusion

In this lesson, we learned about creating special packages called tuples in Python. We explored different things we could do with these tuples, like finding specific parts, taking out only what we needed, and even combining different tuples together. We also talked about how tuples are a bit different from lists.

By using tuples in Python the right way, our code becomes better and stronger. It’s like having a toolbox with special tools that help us organize information neatly and get things done efficiently. Understanding and using tuples can make our code work smarter!