Home
About Us Privacy Policy
 

TUPLES IN PYTHON

ADVERTISEMENT

Intermediate Tuples



What are Tuples?

Tuples are an in-built data type for storing a collection of values or, in simpler terms, storing multiple items in a single variable. Tuples are analogous to lists meaning they can also store item(s) of varying data types but are immutable, meaning changing the values of elements is not permitted. Additionally, the addition or removal of item(s) is prohibited.


Structure of a Tuple



Defining a Tuple

Tuples are declared using two methods:

  • Using the () brackets
  • Using the tuple() method

Example:

# Using the () brackets to define a tuple
a_tuple = (1, 2, 3)
print(a_tuple)
print(type(a_tuple))

(1, 2, 3)
<class 'tuple'>

To inform Python that a tuple is being declared with a single item, always end with a trailing ",".

Example:

a_tuple_with_single_item = (1,)
just_a_single_value = (1)

print(a_tuple_with_single_item, type(a_tuple_with_single_item))
print(just_a_single_value, type(just_a_single_value))

(1,) <class 'tuple'>
1 <class 'int'>

Notice, the the trailing "," after the item "1" in the expression:

a_tuple_with_single_item = (1,)
defines a tuple, whereas the expression
just_a_single_value = (1)
just defines a int object.


Accessing a Tuple

As illustrated in the above diagram, Tuples are accessed using anindex, precisely like Lists are. One of the topics challenging to novices is understanding indexing. Due to improper understanding of indexing, they tend to face many index exceptions or segmentation faults. Therefore, having sound knowledge of tuples and how they are accessed using an index.

The index determines the relative position of the element with offset from the first element.

number = (101, 2, 33, 44, 575, 68, 7, 82, 91)

number[2]
is referring to the value 33
number[0]
is referring to the value 101
number[7]
is referring to the value 82

Remember, indexing of elements starts from 0 and not 1.

The 0'th element refers to the 1'st element. The 1'st element refers to the 2'dn element. The 2'nd index refers to the 3'rd element, and so no.

Try to think about it this way, whenever you want to access any element, think about the number of elements you have to skip. Accordingly, if you're going to access the 0'th element or the very first element, think about how many elements you want to skip. In this case, it's zero(0), so the index will be zero(0). Likewise, if you're going to access the 4'th index (fifth element), you need to skip four(4) elements, so the index is going to be four(4).

Example

numbers = (0, 10, 20, 30, 40, 50, 60, 70, 80, 90)

# To access the value at an index of 4
# I need to skip four elements
fourth_element = numbers[4]   # 5 is the value at this index


ADVERTISEMENT

Converting a list into a tuple using the tuple() method.

The tuple() method accepts an iterator as an argument. Iterator types include lists, string, and iterable objects.

Example:

# Converting a list into a tuple
my_list_of_fav_colors = [ "red", "purple", "orange", "blue"]

# Tuple Method
my_tuple = tuple(my_list_of_fav_colors)
print(my_tuple, type(my_tuple))

('red', 'purple', 'orange', 'blue') <class 'tuple'>


Converting a string into individual items in a Tuple

# Storing individual elements of a string into a tuple
my_name = "Mr. Anderson"
my_tuple = tuple(my_name)
print(my_tuple, type(my_tuple))

('M', 'r', '.', ' ', 'A', 'n', 'd', 'e', 'r', 's', 'o', 'n') <class 'tuple'>


Finding out the length of the tuple

Python provides the in-built len() method to find out the length of the tuple. Here is an example.

# Count the no. of items in a tuple
my_tuple = (1, 20, 33221, 2334, "Hello, World")
length_of_my_tuple = len(my_tuple)
print(length_of_my_tuple)

5


Updating Tuple

Python does not allow for updating the contents of a tuple, but there could be situations where you might need to update the tuple. In such cases, there is a workaround. You can convert the tuple into a mutable type, such as a List, update it, and convert it back to a Tuple.

As discussed in the Lists topic, we can use the in-built list() method to convert an iterable type into a list.

A Tuple is also classified as an Iterable Type.

In the below example, we will be changing the item at 1'st index("Alone in Home") to "Home Alone".

Example:

# Defining a tuple
my_tuple = ("Mr. Anderson", "Alone in Home", "Code: The Matrix")

# Converting into a list
my_list = list(my_tuple)

# Making the changes
my_list[1] = "Home Alone"

# Converting back into a tuple
my_tuple = tuple(my_list)

# Printing out the changes
print(my_tuple, type(my_tuple))

('Mr. Anderson', 'Home Alone', 'Code: The Matrix') <class 'tuple'>


How are items in a Tuple immutable?

In Python programming language, when a tuple is declared, it is marked as immutable, and any priviledge to alter the tuple is revoked. Hence, making it immutable.

Below is an example to demonstrate just that.

# We will use a list because
# we can change its element
my_var = [17, 27, 37, 47]

# Print The ID of the object
print(id(my_var [0]))
print(id(my_var [1]))
print(id(my_var [2]))
print(id(my_var [3]))

9789120
9789440
9789760
9790080

The above output will differ from session to session.

Now, let's change the value of the 0'th element and observe what its id is.

my_var = [17, 27, 37, 47]
print(id(my_var[0]))
my_var[0] = 100
print(id(my_var[0]))

9789120
9791776

The above output will differ from session to session.

As you can observe, whenever we assign a new value to any variable or any index in a List, a new Object of the corresponding data type is created, and its reference is given.

Hence, what we cannot change are the assigned references themselves.

Tuples in Python store references to the object(s) and not the object(s) themselves, and what is prohibited from changing are the references.


ADVERTISEMENT

Storing a List inside a Tuple and Manipulating It

In Python, Tuples are immutable, meaning we cannot alter the value of individual items, as explained above. However, we can manipulate data types that are mutable and sequential.

Example

my_tuple = ("James Bond", [0, 1, 2, 3], 3.14, ("red", "green", "blue"))

# Add a new element to the list within a tuple
my_tuple[1].append(4)

print(my_tuple[1])

[0, 1, 2, 3, 4]

As demonstrated in the above example, we can alter the items in the mutable sequence types, which is the list [0, 1, 2, 3]; however, we cannot replace the list with other data-type nor can delete it, because as explained above we cannot replace the reference with the reference of another object.


Adding a tuple to another

Python allows for adding multiple tuples together to create a new tuple. However, the contents of any of the tuples involved will not change.

Example

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

(1, 2, 3, 4)


Creating a tuple with just one item

As we know that tuples are defined using the () brackets. However, () brackets are also used to prioritize or group an expression for performing operations following the concept of BODMAS(Bracket, Orders, Division, Multiplication, Addition, Subtraction).

Therefore, using () brackets to define a tuple might lead to ambiguity for Python and might cause it to be interpreted as an expression enclosed in (). To inform Python that a tuple is being declared, always add a trailing ",".

Example

a_tuple_with_one_element = (1,)
a_number = (1)

print(a_number, type(a_number))
print(a_tuple_with_one_element , type(a_tuple_with_one_element)

1 <class 'int'> (1,) <class 'tuple'>

Notice, the trailing "," in

a_tuple_with_one_element = (1,)
. The trailing comma(,) informs the Python that a tuple is being declared.

Adding a trailing comma(,) in a tuple with multiple items is optional as there is no ambiguity.


Unpacking a Tuple

When we create a tuple, we might assign it values. This is called "packing" a tuple. Similarly, we can also "unpack" the tuple into individual variables.

This feature will be helpful when passing arguments to functions/methods from a single tuple.

Example

my_colors = ("red", "green", "blue")
red, green, blue = my_colors
print(red, green, blue)

red green blue


Multi Dimensional Tuple

If you have been following this tutorial, in the previous section, we covered multi-dimensional lists. If you haven't gone through lists or skipped multi-dimensional lists, I highly recommend giving it a read before we delve into multi-dimensional tuples.

Multi-dimensional tuples are tuples with another tuple as items. The concept is the same as with lists, but instead, every element is of type tuple.

Below is an illustration to help understand how Python handles them.


The above is the illustration of the below example. The above example shows how we can store multi-dimensional data as items in a tuple.

fruits = (
    ("Apple", "Avocado"),
    ("Blueberries", "Bananas"),
    ("Chinese date", "Cornelian cherry", "Cranberry"),
    ("Dragon fruit", "Damson plum"),
    ("Mango",),
    ("Oranges",),
    ("Kiwi",),
    ("Grape",),
)

for fruit_set in fruits:
    temp = ""
    for fruit in fruit_set:
        temp += fruit + ", "

    # Strip trailing ,(space)
    temp = temp.strip(", ")

    # Print fruit set
    print(temp)

    # Clear the temp variable
    temp = ""

Apple, Avocado
Blueberries, Bananas
Chinese date, Cornelian cherry, Cranberry
Dragon fruit, Damson plum
Mango
Oranges
Kiwi
Grape

A quick exercise.

What would the index be to access the values Grape, Damson plum, Cornelian cherry?

Click to reveal the answer?


ADVERTISEMENT

Looping through a tuple

Since a tuple is iterable, you can loop through it just as you would a list.

Example

my_tuple = (1, 2, 3, 10, 20, 30, 100, 200, 300)
for i in my_tuple:
    print(i)

1
2
3
10
20
30
100
200
300


Looping through a tuple using an index

Example

my_tuple = (1, 2, 3, 10, 20, 30, 100, 200, 300)
index = 0
length_of_tuple = len(my_tuple)
while index < length_of_tuple:
    print(my_tuple[index])
    index += 1

1
2
3
10
20
30
100
200
300


Counting the occurrence of a value in a tuple

Python provides an in-built method count() to count the occurrence of a value in a tuple.

fibonacci = (0, 1, 1, 2, 3, 5, 8, 13)

# Find how many times the value of "1" is present in the tuple?
ones_occurance = fibonacci.count(1)
print(ones_occurance)  # 2

2


Why Use Tuple Instead of a Lists?

Good question. Tuples and Lists are very similar in how they store and process data except for one significant difference. Lists are mutable, meaning they can allow for manipulation, deletion, the addition of element(s). While, Tuples are immutable, meaning that once a tuple is defined, we cannot add, remove or manipulate any item within it.


Conclusion

In this chapter, we learned about the in-built data-structure tuple, the two methods for defining tuples, converting lists and string into a tuple using the in-built tuple() method, finding the number of elements in a tuple using the in-built len() method.

We also learned about the structure of a tuple and how it differs from a list, accessing and updating a tuple, understanding the reason behind immutable elements within a tuple, and updating mutable elements with a tuple.

Furthermore, we also learned about adding tuples together, the syntax for creating a tuple with a single element, unpacking a tuple, and accessing tuples as an iterator, and using a looping structure, brief overview of its methods and advantages of tuples over a list.


ADVERTISEMENT



All product names, logos, and brands are property of their respective owners.