Working with Tuples
Unlike Lists, Tuples are immutable lists, that cannot be modified. A Tuple is created by placing all the items (elements) inside () parenthesis, separated by commas. A Tuple can store data in the form of a string literal, integer or any allowed data type in Python. A tuple can have heterogeneous data items, a tuple can have string and list as data items as well. You can access elements of the tuple using an index. Traverse a tuple using the loop. Nested tuples can be created. Like Lists, we can use slicing with Tuples. There are different methods or operations that can be performed on tuples such as Changing the elements of a tuple, delete operation, membership test, etc.
First of all, we will start with listing difference between Tuples and Lists
Difference b/w List & Tuple
| List | Tuple |
|---|---|
| Elements of a list are Mutable | Elements of a tuple are immutable. |
| When you need to change data over time, list is used. | When you need to use data that does not changes over time, tuple is used. |
| Traversing items in a List is slow as compared to Tuple. | Traversing items in a Tuple is fast as compared to List. |
| Elements of list are enclosed in square bracket. | Elements of a tuple are enclosed in parenthesis. |
Initializing and Traversing a Tuple using index & Loop
In the below code, we will demonstrate, how to initialize a tuple and traverse the tuple using a for loop.
Code:
a = (1, 2, 3, 4, 5, 6)
a_length = len(a)
for i in range(a_length):
print(a[i])
Output:
1 2 3 4 5 6
Negative indexes in tuples
Similar to list and strings we can use negative indexes to access the tuple elements from the end. -1 to access the last element, -2 to access second last and so on.
Using Positive index 0 to n-1 from first to the last element. Using Negative index -1 to -n from last element to the first.
In the below code, we will demonstrate, how to initialize a tuple and traverse the tuple using a for loop.
Code:
a = (1, 2, 3, 4, 5, 6)
a_length = -len(a)
for i in range(-1, a_length-1, -1):
print(a[i])
Output:
6 5 4 3 2 1
Using Nested tuples
Code:
a = (1, 2, 3) # 1Dimensional TUPLE of order 1 by 3
b = (5, 6, 6) # 1Dimensional TUPLE of order 1 by 3
c = (102, 5, -7) # 1Dimensional TUPLE of order 1 by 3
x1 = ((1, 2, 4), (2, 4, 5), (0, 0, 0)) # 2Dimensional TUPLE of order 3 by 3
x2 = ((5, 6, 7), (11, 14, 45), (90, 87, 73)) # 2Dimensional TUPLE 3 by 3
x3 = ((7, 11, 19), (15, 154, 415), (190, 807, 723)) # 2Dimensional TUPLE 3 by 3
d = (a, b, c) # 2Dimensional TUPLE of order 3 by 3
#D1 D2
D1 = len(d)
D2 = len(d[0])
for i in range(D1):
for j in range(D2):
print(d[i][j], end=" ")
print("\t")
print("\n")
x = [x1, x2, x3] # 3Dimensional TUPLE of order 3 by 3 by 3
#X1 X2
X1 = len(x)
X2 = len(x[0])
X3 = len(x[0][0])
for i in range(X1):
for j in range(X2):
for k in range(X3):
print(x[i][j][k], end=" ")
print("\t")
print("\n")
Output:
1 2 3 5 6 6 102 5 -7 1 2 4 2 4 5 0 0 0 5 6 7 11 14 45 90 87 73 7 11 19 15 154 415 190 807 723
Changing & Deleting Elements of a Tuple
We cannot change the elements of a tuple because tuple itself is immutable. However, we can change the elements of nested items that are mutable. For example, in the following code, we are changing the element of the list which is present inside the tuple. List items are mutable that’s why it is allowed.
Tuple elements are immutable which also means that we cannot delete the elements of a tuple. However, deleting entire tuple is possible.
Code:
a = (1, 2, 3, ["I", "Love", "Python"], 4, 5, 6) print(a) a[3][0], a[3][1], a[3][2] = "You", "Hate", "Python" print(a) del a #You will get error, as the tuple is deleted print(a)
Output:
(1, 2, 3, ['I', 'Love', 'Python'], 4, 5, 6)
(1, 2, 3, ['You', 'Hate', 'Python'], 4, 5, 6)
Traceback (most recent call last):
File "practise.py", line 10, in <module>
print(a)
NameError: name 'a' is not defined
Slicing in Tuple
Slices work on Tuple just as with strings and lists, and can also be used to change sub-parts of the Tuple.
Code:
Nordic_Country_Tuple = ("FINLAND", "ICELAND", "NORWAY", "DENMARK", "SWEDEN", "FAROE ISLANDS")
print(Nordic_Country_Tuple[0:1])
print(Nordic_Country_Tuple[0:2])
print(Nordic_Country_Tuple[0:4])
# displaying entire tuple
print(Nordic_Country_Tuple[:])
print(Nordic_Country_Tuple[4:-1])
Output:
('FINLAND',)
('FINLAND', 'ICELAND')
('FINLAND', 'ICELAND', 'NORWAY', 'DENMARK')
('FINLAND', 'ICELAND', 'NORWAY', 'DENMARK', 'SWEDEN', 'FAROE ISLANDS')
('SWEDEN',)
Membership Test in Tuples
in: Checks whether an element exists in the specified tuple.
not in: Checks whether an element does not exist in the specified tuple.
Code:
Nordic_Country_Tuple = ("FINLAND", "ICELAND", "NORWAY", "DENMARK", "SWEDEN", "FAROE ISLANDS")
print("FINLAND" in Nordic_Country_Tuple)
print("ICELAND" in Nordic_Country_Tuple)
print("FAROE ISLANDS" not in Nordic_Country_Tuple)
print("DENMARK" not in Nordic_Country_Tuple)
Output:
True True False False