Tuple in Python
A tuple is similar to a list but there is one difference between a tuple and a list, tuples are immutable means unchangeable. We cannot change its values.
Code
tuple_a = ("red", "yellow", "orange")
print(tuple_a)
PythonOutput: (‘red’, ‘yellow’, ‘orange’) |
Access Item
Access the first item from the tuple.
Code
tuple_a = ("red", "yellow", "orange")
print(tuple_a[1])
PythonOutput: yellow |
Change Specified Item from List
You can also change a third item from a list using its index.
Code
tuple_a = ["red", "yellow", "orange"]
tuple_a[2] = "black" # Modify the third element (index 2) to "black"
print(tuple_a)
PythonOutput: [‘red’, ‘yellow’, ‘black’] |
Print a tuple using for loop
We can also use for loop to print tuple items in one go except printing one by one.
Code
tuple_a = ("red", "yellow", "orange")
for x in tuple_a:
print(x)
PythonOutput: red yellow orange |
Check if the Item exists or not:
Keywords give us the facility to check whether a specified key is present in a dictionary or not:
Code
tuple_a = ("red", "yellow", "orange")
if "red" in tuple_a:
print("Yes 'red' is in the list")
PythonOutput: Yes ‘red’ is in the list |
Add a new item in Tuple
You cannot add a new item to a tuple because as discussed above, tuples are unchangeable.
Code
tuple_a = ("red", "yellow", "orange")
# This will generate an error because tuples are immutable
# tuple_a[3] = "black"
print(tuple_a)
PythonOutput: (‘red’, ‘yellow’, ‘orange’) |
Length of Tuple
Code
Print the number of total Items in the tuple using the len () method:
tuple_a = ("red", "yellow", "orange")
print(len(tuple_a))
PythonOutput: 3 |
Remove item from Tuple
You cannot delete an item from a tuple because as discussed above, tuples are unchangeable.
Code
tuple_a = ("red", "yellow", "orange")
del tuple_a
# This will generate an error because tuple_a is no longer defined
# print(tuple
PythonOutput: NameError: name ‘tuple_a’ is not defined |
Join Two Tuples
We can also join two tuples:
Code
tuple1 = ('one', 'two', 'three')
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
PythonOutput: (‘one’, ‘two’, ‘three’, 1, 2, 3) |
Create a Tuple by using the constructor
We can also create a tuple by using the built-in constructor tuple ():
Code
tuple_b = tuple(("red", "yellow", "orange"))
print(tuple_b)
PythonNote: Note the double-round brackets.
Output: (‘red’, ‘yellow’, ‘orange’) |
Tuple Unpacking
If tuples are in a list then we can unpack tuples using for loop.
Code
my_list = [(1,2), (3,4), (5,6), (7,8)]
for var in my_list:
print(var)
PythonOutput: (1, 2) (3, 4) (5, 6) (7, 8) |
Access First Elements
Assess individual elements of Tuple from the List
Code
my_list = [(1,2), (3,4), (5,6), (7,8)]
for a in my_list:
print(a)
PythonOutput: (1, 2) (3, 4) (5, 6) (7, 8) |
Accessing Second Element
Code
my_list = [(1,2), (3,4), (5,6), (7,8)]
for b in my_list:
print(b)
PythonOutput: (1, 2) (3, 4) (5, 6) (7, 8) |
Author: TCF Editorial
Copyright The Cloudflare.
You can also read these: