PYTHON TUPLES
LEARNING OBJECTIVES
At the end of this chapter students will be able to understand
Declaring/creating list
Initializing tuple values
Accessing tuple elements
Accessing elements from tuples
Indexing method
List slicing method
Adding elements to a tuple
'+' operator
Adding new elements using lists
Updating tuples
Deleting elements from tuples
Del method
Tuple operators
Tuple functions
TUPLES
A tuple is a sequence of comma separated values.
Values in the tuple cannot be modified, i.e. it is immutable.
The values that make up a tuple are called its elements.
Elements in a tuple need not be of the same type.
The comma separated values can be enclosed in parenthesis but parenthesis are not
mandatory.
The index value of tuple starts from 0.
CREATING TUPLES
Tuples can be created by writing comma separated elements/values with or without
parenthesis.
EXAMPLES
>>>tup1=('Sunday', 'Monday', 10, 20)
>>>tup2=('a', 'b', 'c', 'd', 'e')
>>> tup3=(1,2,3,4,5,6,7,8,9)
>>> tup4=(10,) # tuple with one element
>>>tup5=() # empty tuple
NOTE:
Here tup4 is a tuple with one single value. The final comma after single value is
mandatory otherwise it is not considered as tuple.
>>> tup6= (100)
>>> type(tup6)
<class 'int'>
Here tup6 is considered as integer not as tuple.
>>> tup6= (100,)
>>> type(tup6)
<class 'tuple'>
Now, tup6 is considered as a tuple.
tuple() function
An empty tuple can be created using tuple() function.
>>> tup7=tuple()
Here tup7 is an empty tuple.
CREATING A TUPLE FROM AN ALREADY EXISTING TUPLE
Consider the following tuples:
>>>tuple1=(100, 200, 300, 400, 500)
>>>tuple2=(90, 100, 200, 300,40)
>>>tuple3= ('A', 'E', 'I', 'O', 'U')
>>>tuple5=tuple1[:]
tuple5 is a copy of tuple1
tuple5=(100, 200, 300, 400, 500)
>>>tuple6=tuple2[1:4]
tuple6 will contain elements 1,2,3 of tuple2
tuple6=(100, 200, 300)
>>>tuple7=tuple1
tuple7 will contain all elements of tuple1
tuple7=(100, 200, 300, 400, 500)
INITIALIZING TUPLE VALUES
We can initialize the tuple values using the following method:
EXAMPLE
>>> t=tuple()
>>> t=(10,)*10
>>> print(t)
OUTPUT
(10, 10, 10, 10, 10, 10, 10, 10, 10, 10)
ACCESSING TUPLE ELEMENTS
INDEXING METHOD
Elements of a tuple can be accessed using an indexing method.
Tuple indices start at 0.
The tuple index has to be a positive or negative integer value or an expression which
evaluates to an integer value. Positive value of index means counting forward from
beginning of the tuple and negative value means counting backward from end of the
tuple.
An Index Error appears, if we try to access element that does not exist in the tuple.
If the total number of elements in the tuple is max, then:
Index value
element in the list
0, -max
1st
1, -max+1
2nd
2, -max+2
3rd
........
max-2, -2
2nd last
max-1, -1
last
To access an element, present at a particular index square brackets along with the
desired index number is given.
SYNTAX
tuple-name [ index-number]
EXAMPLE 1
>>> t=('A', 'B', 'C')
>>> print(t[2])
OUTPUT
EXAMPLE 2
>>> t=('A', 'B', 'C')
>>> print(t[-2])
OUTPUT
EXAMPLE 3
>>> t=('A', 'B', 'C')
>>> print(t[2*1])
OUTPUT
TUPLE SLICING
Slicing is used to retrieve a subset of values. A slice of a tuple is basically its sub-tuple.
SYNTAX
tuple-name [start: stop: step]
where
start is the starting point
stop is the stopping point
step is the step size - also known as stride
NOTE:
If you omit first index, slice starts from “0‟ and omitting of stop will take it to end.
Default value of step is 1.
It includes the first element but excludes the last element.
EXAMPLE
Consider a tuple z1 with values
z1=(10,20,30,40,50,60)
z1[:]
(10,20,30,40,50,60)
z1[2:5]
(30,40,50)
z1[:5]
(10,20,30,40,50)
z1[3:]
(40,50,60)
z1[::2]
(10,30,50) (from beginning till end in step 2)
z1[::-2]
(60,40,20) (from end till beginning in step 2)
z1[-5:-2]
(20,30,40)
z1[Link]-1]
(60,50,40)
z1[-2:-5:-1]
(50,40,30)
z1[-2:-5:-2]
(50,30)
ADDING ELEMENTS TO A TUPLE
'+' OPERATOR
New elements can be added to a tuple using '+' operator.
EXAMPLE 1
>>> t=tuple()
>>> t=t+(10,20)
>>> print(t)
OUTPUT
(10, 20)
EXAMPLE 2
>>> t=('A', 'B', 'C')
>>> t=t+ (10,)
>>> print(t)
OUTPUT
('A', 'B', 'C', 10)
NOTE : We can only add tuple to a tuple.
EXAMPLE 3
>>> t=('A', 'B', 'C')
>>> t=t+ 10
OUTPUT
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
t=t+ 10
TypeError: can only concatenate tuple (not "int") to tuple
ADDING NEW ELEMENTS USING LIST
To add new elements to a tuple using list follow these steps:
Convert tuple to list
Add elements to list using append function
After adding elements convert list to tuple
Consider the following code:
>>> tup1=tuple() #create empty tuple
>>> list1=list(tup1) #convert tuple into list
>>> [Link](100) #Add new elements to list
>>> [Link](200)
>>> tup1=tuple(list1) #convert list into tuple
>>> print (tup1)
OUTPUT
(100, 200)
UPDATING TUPLES
Tuples are immutable which means you cannot update or change the values of tuple
elements.
DELETING TUPLE ELEMENTS
Removing individual tuple elements is not possible.
To explicitly remove an entire tuple, just use the del statement. For example
>>> del z1
NOTE : If we try to access a tuple after deleting it, it will result in error.
>>> print(z1)
Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
print(z1)
NameError: name 'z1' is not defined
TUPLE OPERATIONS
Length
>>> len((10, 20, 30))
>>> z1=('a', 'b', 'c', 'd')
>>> len(z1)
Concatenation
>>> (10, 20, 30) + (40, 50, 60)
>>> z2=(10, 20, 30, 40, 50, 60)
>>> z3=(30, 40)
>>> z4=z2+z3
>>> print(z4)
(10, 20, 30, 40, 50, 60)
(10, 20, 30, 40, 50, 60, 30, 40)
Repetition
>>> ('true',) * 4
>>> z3=(30, 40)
>>> z3*2
('true', 'true', 'true', 'true')
(30, 40, 30, 40)
Membership
>>> 2 in (1, 2, 3)
>>> z2=(10, 20, 30, 40, 50, 60)
>>> 10 in z2
True
True
Iteration
for a in (1, 2, 3):
print a,
123
Swapping
>>> z2=(10, 20, 30, 40, 50, 60)
>>> z3=(30, 40)
>>> z2,z3=z3,z2
>>> print(z2)
>>> print(z3)
(30, 40)
(10, 20, 30, 40, 50, 60)
PYTHON TUPLE FUNCTIONS
FUNCTION
EXPLANATION
EXAMPLE
len()
Returns the length of the tuple
SYNTAX:
len(tuple-name)
>>> tuple1=[100, 200, 50, 400, 500, 'Raman', 100, 'Ashwin']
>>> len(tuple1)
max()
Returns the element with maximum value from the tuple
NOTE: To use the max() function all values in the tuple must be of same type
>>> tuple3=[10,20,30,40]
>>> max(tuple3)
40
>>> tuple4=['A', 'a', 'B','C']
>>> max(tuple4)
'a'
here it will return the alphabet with maximum ASCII value
>>> tuple5=['ashwin','bharat','shelly']
>>> max(tuple5)
'shelly'
here it will return the string which starts with character having highest ASCII value.
>>> tuple5=['ashwin','bharat','shelly', 'surpreet']
>>> max(tuple5)
'surpreet'
If there are two or more string which start with the same character, then the second
character is compared and so on.
min()
Returns the element with minimum value from the tuple
NOTE: To use the min() function all values in the tuple must be of same type
>>> tuple3=[10,20,30,40]
>>> min(tuple3)
10
>>> tuple4=['A', 'a', 'B','C']
>>> min(tuple4)
'A'
here it will return the alphabet with minimum ASCII value
>>> tuple5=['ashwin','bharat','shelly']
>>> min(tuple5)
'ashwin'
here it will return the string which starts with character having smallest ASCII value.
>>> tuple5=['ashwin','bharat','shelly', 'surpreet']
>>> min(tuple5)
'ashwin'
If there are two or more string which start with the same character, then the second
character is compared and so on.
count()
It is used to count the occurrences of an item in the tuple.
>>> tuple6=[10,20,10,30,10,40,50]
>>> [Link](10)
3