By: Archana Shukla and Rajesh Shukla
Tuple
A tuple is a sequence of python immutable objects. It is enclosed within parenthesis ().
Creating a tuple
>>> tup1=(1,2,3,4)
>>> tup1
(1, 2, 3, 4)
Accessing tuple items
Items of tuple can be accessed through index.
Example
>>> tup1=('red','blue','green','yellow') >>> tup1[2]
Output
‘green’
Items of tuple can also be accessed through negative index.
Example
>>> tup1=('red','blue','green','yellow') >>> tup1[-1]
Output
‘yellow’
Items of tuple can also be accessed through range of index.
Example
>>> tup1='red','blue','green','yellow','orange','brown') >>> tup1[2:4] >>> tup1[-5:-2] >>> tup1[-3:] >>> tup1[:4] >>> tup1[0:4:2]
Output
(‘green’, ‘yellow’)
(‘blue’, ‘green’, ‘yellow’)
(‘yellow’, ‘orange’, ‘brown’)
(‘red’, ‘blue’, ‘green’, ‘yellow’)
(‘red’, ‘green’)
Iteration through a tuple
We can access elements of a tuple using loop.
Example 1:
tup1=(1,2,3,4,5,6,7,8,9,10)
for i in tup1:
print(i)
Example 2: using range() function
tup1=(1,2,3,4,5,6,7,8,9,10)
for i in range(len(tup1)):
print(tup1[i])
Concatenation of tuple
We can add two tuples with ‘+’ operator.
Example:
>>> t1=(1,2,3,4) >>> t2=('a','b','c') >>> t1+t2
Output
(1, 2, 3, 4, ‘a’, ‘b’, ‘c’)
Repetition of tuple
We can use ‘*’ to multiply the tuple number of times.
Example:
>>> t1=(1,2,3,4) >>> t1*3
Output
(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)
Membership
We can use ‘in’ to check whether the specified element is present in the tuple or not.
Example:
>>> t1=(1,2,3,4) >>> 5 in t1
Output
False
Creating tuple with one item
To create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple.
Example
>>> tup1=(‘orange’,)
>>> print(type(tup1))
<class ‘tuple’>
Example
>>> tup1=(‘orange’)
>>> print(type(tup1))
<class ‘str’>
Tuple functions
Function | Description | Example |
len(tuple) | Returns total no of items in the tuple | >>>tup=(‘a’,’b’,’c’) >>>print(len(tup)) 3 |
max(tuple) | Returns the item with largest value in the tuple | >>> tup=(2,60,455,120,3,5) >>> print(max(tup)) 455 |
min(tuple) | Returns the item with smallest value in the tuple | >>> tup=(2,60,455,120,3,5) >>> print(min(tup)) 2 |
tuple(seq) | Converts a list or string into a tuple | >>> str=”hello” >>> t=tuple(str) >>> t (‘h’, ‘e’, ‘l’, ‘l’, ‘o’) |
Tuple Methods
Python has two built-in methods that you can use on tuples.
count() | Returns the number of elements with the specified value | >>> t1=(1,2,3,1,4,5,1,6,1,8) >>> t1.count(1) 4 |
index() | Returns the index of the first element with the specified value | >>> t1.index(4) 4 |