You are on page 1of 2

Python – TUPLE data type

A tuple is a sequence of comma separated values (items) enclosed in round brackets.


Items in the tuple may have different data types.
T1 = (‘Aman’, 12, 4500, ‘Jatin’, 34, 8793) # A tuple with integer and string values
T2 = (12, ‘Monica’, 89.8, ‘Shilpa’, (45, 67), 78.5) # A tuple within a tuple - Nested Tuple
T3 = (‘E001’, [‘D01’, T05’], 23, 12) # A tuple having a list
T4 = ( ) # T4 is an empty tuple with no contents
T5 = ( 23, ) # Tuple with a single value has a comma at the end

Tuple List
Tuple is immutable i.e., its contents cannot List is mutable i.e., its contents can be changed or
be changed or removed. removed.
The elements in tuple are within parentheses. The elements in List are within square brackets.
Example, T1 = (‘Manish’, 12, 345) Example, L1 = [‘Manish’, 12, 345]
Basic Tuple Operations
Operation Expression Results
Concatenation a = (2, 4, 6)
b = (5, 7, 9)
c=a+b
print ( c, b, a, sep="~~") (2, 4, 6, 5, 7, 9)~~(5, 7, 9)~~(2, 4, 6)
Repetition t = (“welcome”,)
print ( t * 2 ) (‘welcome’, ‘welcome’)
Membership nos = ( 1, 3, 5,7 )
4 in nos False
3 in nos True
2 not in nos True
Tuple Slicing
0 1 2 3
Like string indices, tuple indices also start at 0, and can be sliced.
‘monica’ 12 ‘seema’ (13,17)
T1 = ( ‘monica’,12,’seema’, (13,17 ) )
-4 -3 -2 -1

Slicing operation Result Explanation


T1[1] 12 Returns the second item in the tuple
T1[1:4] (12,’seema’, ( 13 , 17 )) Returns elements from index 1 to 3
T1[1:-2] (12,) Returns element from 1, stops before -2
T1[ : 3] (‘monica’,12,’seema’) Returns elements from index 0 to index 2
T1[2: ] ('seema', (13, 17)) Returns elements from index 2 till the end
T1[2] = ‘garima’ Error Because tuple is immutable, values cannot be changed
del T1 Removes entire tuple T1
Note: You cannot remove individual elements of a tuple
Built-in Tuple Functions
Function Description Example Result
a = ( 10,20,30,40)
len(t1) Returns number of elements in tuple t1 len(a) 4
max(t1) Returns the element with maximum value in t1 max(a) 40
min(t1) Returns the element with minimum value in t1 min(a) 10
sum(t1) Returns the sum of all the elements in the tuple t1 sum(a) 100
list(t1) Converts the tuple t1 to a list data type list(a) [10,20,30,40]
Changing Tuple Values
Individual items of a tuple cannot be changed once assigned. But, if the element is itself a mutable data
type, like a list, its nested items can be changed.
Example:
a = (10,20,[30,40],50) 0 1 20 21 3
a[2][0] =60 # list value changed 10 20 30 40 50
print(a) The value 30 can be referenced as a[2][0]
(10, 20, [60, 40], 50) The value 40 can be referenced as a[2][1]

a[0] =100 # error, because tuple value cannot be changed

Deleteing Tuple values


del a[0] # error, because individual tuple value cannot be deleted
del a[2][1] # since a[2][1] is nested list , its values can be changed or deleted
print(a)
(10, 20, [60], 50)

You might also like