10) Python Review Tuple in Python
10) Python Review Tuple in Python
Tuple is a standard data type of Python that can store a sequence of values of any data
type in parenthesis( ). Tuple is immutable i.e. we can not change the elements of tuple.
Examples:
( ) – empty tuple
(2,3,4,5) – tuple of integer
(2.5, 3.2, 4.5) – tuple of decimal number(float)
(‘a’, ’b’, ’c’) – tuple of characters
(2, ’a’, 3.2, 8, 9 , ’b’) – tuple of mixed values
2. Using tuple() method :- It create a individual element of tuple from the individual
element of the specified sequence as givren below.
Syntax : T = tuple(sequence)
Here sequence can be string, list or tuple
Examples:-
>>>T = tuple(“abc”) >>>L=[1,3,5,7] >>>T1=(3,2,8,7)
>>>T >>>T = tuple(L) >>>T2 = tuple(T1)
(‘a’, ’b’, ’c’) >>>T >>>T2
(1,3,5,7) (3,2,8,7)
3. Using input() method :- We can also enter tuple elements during the execution of
program as follows:
Syntax : T = tuple(input(“Enter elements of tuple : ”))
As we know that input() take the value from the user in form of string So the above
syntax will create a tuple of character. Because tuple() will take the argument as string.
Example:
Output: Output:
Enter any value: [4,2,6,7,8] Enter any value: (2,3,4,5)
[4,2,6,7,8] (2,3,4,5)
Nested Tuple:-
If the elemet of tuple is itself a tuple then that tuple is called Nested tuple.
Example:-
P = ( 2, 4, 5, (1,2), (5,8,9) )
Indexing, Accessing and Traversing tuple elements:-
Indexing in tuple is similar to indexing in List. The individual element of tuple is
accessed by the help of its index. There are two types of indexing:
Forward Indexing and Backword Indexing
Example:- T = (4,7,9,8,20,15,12)
Forward indexing
0 1 2 3 4 5 6
4 7 9 8 20 15 12
-7 -6 -5 -4 -3 -2 -1
Backword indexing
Traversing tuple elements Using len( ) function:
T = (2,4,6,8) Output: T = (2,4,6,8) Output:
for a in T: 2 p = len(T) 2
print(a) 4 for a in range(0,p): 4
6 print(a) 6
8 8
TUPLE OPERATIONS
Joining the Tuples using concatenation operator(+) :- This operator creates a new tuple
by joining two tuples.
Example:
>>>T=(1,2,3,5,9,2,4,2) >>>T=(5,3,5,9,2,4)
>>>T.count(2) >>>T.count(8)
3 0