What is a Tuple?
A tuple is a Sequence Data Type in Python. It consists of a number of values inside parentheses instead of square brackets, separated by commas. Tuples can contain multiple values, making writing programs that handle large amounts of data more accessible. These values can be Homogenous or Heterogenous(i.e., different data types). Tuples like strings are immutable. Tuples cannot have their values modified, appended, or removed. Its elements cannot be modified individually. Though, tuples can be reassigned to a new set of elements.
How are Tuples created?
A Tuple is created by putting the elements inside parentheses (), separated by commas.
# Creating a tuple(Homogeneous Elements) my_tuple = ('t','u','p','l','e') # Creating a tuple(Heterogeneous Elements) my_tuple2 = (1, 'Tuple', 2, 3, 4, 5) print(my_tuple) print(my_tuple2)
Tuples can also be nested, like this:
my_tuple = ('t','u','p','l','e') my_tuple2 = (my_tuple, 1, 2, 3, 4, 5) print(my_tuple2)
You can create Tuple with a single element, by placing a trailing comma after the value inside the parentheses. else it will be treated as a single value inside regular parentheses. Tuple with a single element can be created like this:
my_tuple = (2,) print(my_tuple)
How Tuple elements can be accessed?
Elements of a tuple can be accessed by referring to the index number. An index number is provided inside the square brackets [ ].
my_tuple = ('t','u','p','l','e') print(my_tuple)
Elements inside a tuple can also be accessed through slicing.
my_tuple = ('t','u','p','l','e') print(my_tuple[2:4]) print(my_tuple[:4]) print(my_tuple[1:]) print(my_tuple[:-4])
How Tuples can be modified?
Since tuples are immutable, elements of a tuple cannot be changed once they have been assigned. But, if the element is a mutable data type as a list, its nested items can be changed. We can also assign a tuple to different values.
# Changing tuple values my_tuple = (4, 2, 3, [6, 5]) # item of mutable element can be changed my_tuple = 9 print(my_tuple) # Tuples can be reassigned my_tuple = ('t','u','p','l','e') print(my_tuple)
How to Delete a Tuple?
Tuples can be deleted using the del keyword in python.
# Deleting tuples my_tuple = ('t','u','p','l','e') # can't delete items # del my_tuple # Can delete an entire tuple del my_tuple # NameError: name 'my_tuple' is not defined print(my_tuple)
This operation adds all the elements of the operand tuples into a new tuple.
my_tuple = (2, 5, 0) + (1, 3) + (4,) print(my_tuple)
Multiplying a tuple by an integer, x will create another tuple with all the elements from the first tuple repeated x a number of times.
my_tuple = (2, 5, 0) * 4 print(my_tuple)
It is used to check if any element is present in the sequence or not. It returns True if the element is found, otherwise False.
my_tuple = (2, 5, 0) print(2 in my_tuple) print(3 in my_tuple)