Traversing a Tuple and Tuple Operators:
M3-R5.1 · Chapter 5: Sequence Data Types · 3 min read
Traversing a Tuple:
Syntax: for <variable> in tuple-name:
Statement
|
Method-1 |
Method-2 |
||
|
jai=('q','w','e','r','t','y') for i in jai: print(i) Output: q w e r t y |
jai=('q','w','e','r','t','y') for i in range(0, len(jai)): print(jai[i]) Output: q w e r t y |
||
|
Q.: Find the length of a tuple. tup = (1, 2, 3, 4, 5) length = len(tup) print(length) |
Q: Find the length of a tuple without len function. jai = (1, 2, 3, 4, 5) c=0 for i in jai: c=c+1 print(c) |
||
|
Q: print the even no in a tuple. jai = (1, 2, 3, 4, 5) c=0 for i in jai: if(i%2==0): print(i) |
Q: Write a program to print the sum of all tuple elements. jai = (1, 2, 3, 4, 5) sum=0 for i in jai: sum=sum+i print(sum) |
||
Tuple Operations:
- Joining operator +
- Repetition operator *
- Slice operator [ : ]
- Comparison Operator <, <=, >, >=, ==, !=
Joining Operator: It joins two or more tuples we can use + Operator
|
>>> T1 = (25,50,75) >>> T2 = (5,10,15) >>> T1+T2 Output: (25, 50, 75, 5, 10, 15) |
tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3) |
>>> T1 + (34) # TypeError: can only concatenate tuple (not "int") to tuple
>>> T1 + (34, ) Output: (25, 50, 75, 34)
Repetition Operator: It replicates a tuple, specified number of times. Or If you want to multiply the content of a tuple a given number of times, you can use the * operator:
Example:
>>> T1*2
(25, 50, 75, 25, 50, 75)
>>> T2=(10,20,30,40)
>>> T2[2:4]*3
(30, 40, 30, 40, 30, 40)