TUPLES
TUPLES
print(thistuple)
To create a tuple with only one item, add a comma after the item, otherwise Python will not
recognize it as a tuple.
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
<class 'tuple'>
<class 'str'>
The tuple() Constructor
CREATING TUPLE
T1=eval(input("Enter tuple to be added :"))
Enter tuple to be added :(2,5,6,7,8,9)
print(T1)
(2, 5, 6, 7, 8, 9)
TUPLE OPERATIONS
1.Traversing
Tuple1 = (1, 2, 3, 4, 5, 6)
print(Tuple1)
for i in Tuple1:
print(i)
for i in range(len(Tuple1)):
print(Tuple1[i])
(1, 2, 3, 4, 5, 6)
1
2
3
4
5
6
1
2
3
4
5
6
2.Joining
Tuple1 = (1, 2, 3, 4, 5, 6)
Tuple2=(11,22,33,44,55)
print(Tuple1+Tuple2)
(1, 2, 3, 4, 5, 6, 11, 22, 33, 44, 55)
3.Repeating or Replicating
print(Tuple1*3)
(1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6)
4.Slicing
tuple= ('a','b','c','d','e','f','g','h','i','j')
print(tuple[0:6])
print(tuple[1:9:2])
print(tuple[-1:-5:-2])
5.UnPacking Tuples
When we create a tuple, we normally assign values to it. This is called "packing" a tuple:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
apple
banana
cherry
res = Tuple1.count(3)
print('Count of 3 in Tuple1 is:', res)
res = Tuple2.count('python')
print('Count of Python in Tuple2 is:', res)