Tuples
Tuples
A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list
or even a tuple. Elements of a tuple are enclosed in parenthesis (round brackets) and are separated
by commas. Like list and string, elements of a tuple can be accessed using index values, starting from
0.
**If there is only a single element in a tuple then the element should be followed by a comma. If
we assign the value without comma it is treated as integer. It should be noted that a sequence
without parenthesis is treated as tuple by default.
Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing.
>>> tuple1[0]
>>> tuple1[3]
Tuple is Immutable –
Tuple is an immutable data type. It means that the elements of a tuple cannot be changed after it
has been created.
>>> tuple2[3][1] = 10
TUPLE OPERATIONS –
Concatenation-
tuple1 = (1,3,5,7,9)
tuple2 = (2,4,6,8,10)
tuple1 + tuple2
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
Repetition-
tuple1 = ('Hello','World')
tuple1 * 3
Membership
The in operator checks if the element is present in the tuple and returns True, else it returns False.
tuple1 = ('Red','Green','Blue')
'Green' in tuple1
True
The not in operator returns True if the element is not present in the tuple, else it returns False.
tuple1 = ('Red','Green','Blue')
False
Slicing-
tuple1 = (10,20,30,40,50,60,70,80)
tuple1[2:7]
tuple1[0:len(tuple1)]
tuple1[:5]
tuple1[2:]
tuple1[0:len(tuple1):2]
tuple1[-6:-4]
(30, 40)
tuple1[::-1]
It allows a tuple of variables on the left side of the assignment operator to be assigned respective
values from a tuple on the right side. The number of variables on the left should be same as the
number of elements in the tuple.
and
>>> print(num1)
10
>>> print(num2)
20
NESTED TUPLES –