A tuple is a sequence of immutable objects enclosed in parentheses (). The main difference between tuples and lists is that the tuples can't be changed, whereas lists can be changed.
Creating a tuple: The following example shows how to create tuple.
tuple1 = (10, 20, 30, 40, 50)
print(tuple1)
(10, 20, 30, 40, 50)
Accessing Tuple Values: To access tuple values, use index or indices of an element. Indexes starts from 0, index value of 1st element is 0, 2nd element is 1 and so on. Python also supports negative indexes which are count from right.
tuple1 = (10, 20, 30, 40, 50)
print("Value at index 2 is:",tuple1[2])
print("Value at index -2 is:",tuple1[-2])
Value at index 2 is: 30
Value at index -2 is: 40
Updating Tuple: Tuples are immutable, which means you can't update or change the values of tuple.
Deleting Tuple Elements: Removing individual tuple elements is not possible. To explicitly remove an entire tuple, just use del statement
Basic Tuple Operations:+ Concatenate two tuple and result is a new tuple.
tuple1 = (10, 20, 30)
tuple2 = (40, 50)
print("tuple1 + tuple2 is",tuple1+tuple2)
tuple1 + tuple2 is (10, 20, 30, 40, 50)
* Repetition of tuple for N times and result is a new tuple.
tuple1 = (10, 20, 30)
print("tuple1 * 2 is",tuple1*2)
tuple1 * 2 is (10, 20, 30, 10, 20, 30)
in Membership operator which returns True when element present in tuple. False otherwise.
tuple1 = (10, 20, 30)
print("20 in tuple1 ",20 in tuple1)
print("40 in tuple1 ",40 in tuple1)
True
False
[start:stop:step] Gives access to a specified range of sequence’s elements.
tuple1 = (10, 20, 30, 40, 50)
print("tuple1[::] is",tuple1[::])
print("tuple1[2:] is",tuple1[2:])
print("tuple1[:3] is",tuple1[:3])
print("tuple1[::-1] is",tuple1[::-1])
tuple1[::] is (10, 20, 30, 40, 50)
tuple1[2:] is (30, 40, 50)
tuple1[:3] is (10, 20, 30)
tuple1[::-1] is (50, 40, 30, 20, 10)