Python

Tuple In Python With An Example – Q&A

A tuple is comparable to a list in Python, but tuples’ objects are immutable, meaning that once they have been assigned, they cannot be changed. On the other side, we can modify a list’s elements.

1. List vs. Tuple

1. A tuple’s elements are immutable, but a list’s elements are mutable.
2. Tuple is the preferred data type when we don’t want to change the data over time, however list would be the smart choice if we need to change the data in the future.
3. Comparing iterating over a list to iterating over the elements of a tuple, the latter is quicker.
4. The items of a list are enclosed in square brackets, while the components of a tuple are enclosed in parentheses.

2. Python tuple creation instructions

Put all the items in a () parenthesis, separated by commas, to form a tuple in Python. A tuple can include both string and list data pieces in addition to heterogeneous data items.

2.1 Tuple creation example

We’re making a small number of tuples in this example. Both tuples of the same type of data and mixed tuples of different types of data are possible. This illustration also includes nested tuples (tuples as data items in another tuple).

# tuple of strings
my_data = ("hi", "hello", "bye")
print(my_data)

# tuple of int, float, string
my_data2 = (1, 2.8, "Hello World")
print(my_data2)

# tuple of string and list
my_data3 = ("Book", [1, 2, 3])
print(my_data3)

# tuples inside another tuple
# nested tuple
my_data4 = ((2, 3, 4), (1, 2, "hi"))
print(my_data4)

Output:

('hi', 'hello', 'bye')
(1, 2.8, 'Hello World')
('Book', [1, 2, 3])
((2, 3, 4), (1, 2, 'hi'))

2.2 Empty tuple:

# empty tuple
my_data = ()

2.3 Single-element tuples:

If there is only one element in a tuple, a comma must come after it in order for Python to recognize it as such.

# a tuple with single data item
my_data = (99,)

Python will regard my data as an int variable rather than a tuple if there is no comma following the number 99 in the example above.

3. Getting at tuple elements

To retrieve a tuple’s elements, we employ indexes. To further grasp how it works, let’s look at a few examples.

3.1 Using positive indexes to access tuple elements

As we will explore in the section after this, tuples can also have negative indexes. Since indexes begin at 0, we use 0 to access the first tuple element, 1 to access the second, and so on.

# tuple of strings
my_data = ("hi", "hello", "bye")

# displaying all elements
print(my_data)

# accessing first element
# prints "hi"
print(my_data[0])

# accessing third element
# prints "bye"
print(my_data[2])

Output:

('hi', 'hello', 'bye')
hi
bye

Note:

1. TypeError will occur if integer indexes are not used in the tuple. For instance, this error will be raised by my data[2.0]. An integer must always be used as the index.
IndexError: Index outside range, second. When we mention an index that is outside of the range, an error happens. This error might arise, for instance, if a tuple contains 5 elements and we attempt to access the 7th element.

3.2 Negative tuple indexes

We can use negative indexes to retrieve the tuple elements from the end, just like with lists and strings.
Access the final element with -1, the next element with -2, and so forth.

my_data = (1, 2, "Kevin", 8.9)

# accessing last element
# prints 8.9
print(my_data[-1])

# prints 2
print(my_data[-3])

Output:

8.9
2

3.3 Using nested tuples to access elements
Let’s examine how the nested tuple elements are accessed using double indexes. The main tuple element is represented by the first index, and the nested tuple element is represented by the second index.

When I used my data[2][1] in the example below, it accessed the second element of the nested tuple. Due to the fact that 1 represented the second member of the main tuple and 2 represented its third element.

my_data = (1, "Steve", (11, 22, 33))

# prints 'v'
print(my_data[1][3])

# prints 22
print(my_data[2][1])

Output:

v
22

4. Python operations that can be carried out on tuples

Let’s look at the Python operations that can be applied to tuples.

4.1 Modifying a tuple’s components

The components of a tuple are immutable, thus we cannot alter them. The mutable constituents of nested items, however, are modifiable. For instance, in the code below, we are modifying the list element that is contained within the tuple. It is permitted since list items are mutable.

my_data = (1, [9, 8, 7], "World")
print(my_data)

# changing the element of the list
# this is valid because list is mutable
my_data[1][2] = 99
print(my_data)

# changing the element of tuple
# This is not valid since tuple elements are immutable
# TypeError: 'tuple' object does not support item assignment
# my_data[0] = 101
# print(my_data)

Output:

(1, [9, 8, 7], 'World')
(1, [9, 8, 99], 'World')

4.2 Tuple delete operation

The fact that tuple elements are immutable, as we have stated before, also means that we cannot remove a tuple’s elements. However, a whole tuple can be deleted.

my_data = (1, 2, 3, 4, 5, 6)
print(my_data)

# not possible
# error
# del my_data[2]

# deleting entire tuple is possible
del my_data

# not possible
# error
# because my_data is deleted
# print(my_data)

Output:

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

4.3 Slicing operation in tuples

my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data)

# elements from 3rd to 5th
# prints (33, 44, 55)
print(my_data[2:5])

# elements from start to 4th
# prints (11, 22, 33, 44)
print(my_data[:4])

# elements from 5th to end
# prints (55, 66, 77, 88, 99)
print(my_data[4:])

# elements from 5th to second last
# prints (55, 66, 77, 88)
print(my_data[4:-1])

# displaying entire tuple
print(my_data[:])

Output:

(11, 22, 33, 44, 55, 66, 77, 88, 99)
(33, 44, 55)
(11, 22, 33, 44)
(55, 66, 77, 88, 99)
(55, 66, 77, 88)
(11, 22, 33, 44, 55, 66, 77, 88, 99)

4.4 Tuples Membership Test in:

Determines if an element is present in the given tuple.
not in: Verifies whether a given element is absent from the given tuple.

my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data)

# true
print(22 in my_data)

# false
print(2 in my_data)

# false
print(88 not in my_data)

# true
print(101 not in my_data)

Output:

(11, 22, 33, 44, 55, 66, 77, 88, 99)
True
False
False
True

4.5 Iterating a tuple

# tuple of fruits
my_tuple = ("Apple", "Orange", "Grapes", "Banana")

# iterating over tuple elements
for fruit in my_tuple:
     print(fruit)

Output:

Apple
Orange
Grapes
Banana

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button