This document discusses tuples in Python. It begins with definitions of tuples, noting that they are ordered, indexed and immutable sequences. It then provides examples of creating tuples using parentheses or not, and explains that a single element tuple requires a trailing comma. The document discusses tuple operations like slicing, comparison, assignment and using tuples as function return values or dictionary keys. It also covers built-in tuple methods and functions.
2. INDEX
1. 10.1-Tuples are immutable
2. 10.2-ComparingTuples
3. 10.3-Tuple assignment
4. 10.4-Dictionaries and tuples
5. 10.5-Multiple assignment with dictionaries
6. 10.6-The most common word
7. 10.7-UsingTuples as keys in dictionaries
What is python tuples ?
1
How to create python tuple
2
Parentheses in python tuple
3
Tuples are immutable
4
Python tuples for single item
5
Slicing in python tuples
6
Tuples as return values
7
Variable-length arguments
8
Python tuple functions
9
Python tuple methods
Iterations on python tuple
Dictionaries and python
TABLE OF CONTENTS
10
11
12 2
3. WHAT IS PYTHON TUPLES ?
Tuples is a sequence data type which are ordered, indexed and immutable .
A Tuple is a collection of Python objects separated by commas. May or may not
be enclosed within parentheses.
Elements of the tuple may be numbers, strings or other data type like Lists
Elements in the tuple can be extracted using square-brackets with the help of
indices. Similarly, slicing also can be applied to extract required number of items
from tuple
Tuple may contain single element also or we may create an empty tuple
Tuples allow duplicate elements to be present and are indexed
Tuples are comparable and hashable objects. Hence, they can be made as keys in
dictionaries 3
4. HOW TO CREATE A PYTHON TUPLE ?
• SS
Syntactically, a tuple is a list of items separated by commas, inside a parenthesis.
Can be assigned to a tuple object.
>>> my_group = ('Govindaraju N’,'Akshatha p’,'Vinay’,'Abhishek’)
>>> type(my_group)
<class 'tuple’>
>>> print(my_group)
('Govindaraju N', 'Akshatha p', 'Vinay', 'Abhishek')
>>> my_tuple=(1, 2, ‘Krishna’, 45.67)
>>>print (my_tuple)
(1, 2, 'krishna', 45.67)
4
5. PARENTHESIS REQUIRED IN PYTHON TUPLES ?
th
Parentheses is not really necessary for python tuples. But, it’s a good practice to
use them. This is called tuple packing.
Yess…! We get the output without parenthesis.
t='a','b','c','d','e'
print(t, type(t))
Output:
('a', 'b', 'c', 'd', 'e') <class
'tuple'>
t=1,2,3,4,5,6
print(t, type(t))
Output:
(1,2,3,4,5,6) <class 'tuple'>
5
6. TUPLES ARE IMMUTABLE
• SS
We cannot change the elements of a tuple once assigned.
Lets try changing a value and check :
>>> my_tuple = (1,2,3,[6,5]) #lets try to change the element at index 1
>>> my_tuple[1] = 10
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
my_tuple[1]=10
TypeError: 'tuple' object does not support item assignment
6
7. • SS
Ooh!... we failed to get our desired output
Now how about changing an element from the list contained in a tuple ?
Yess…! It worked without a flaw. So we came to know that while tuples are
immutable, a mutable item that it holds may be reassigned.
>>> my_tuple = (1,2,3,[6,5])
>>> my_tuple[3][0] = 10
>>> print (my_tuple)
(1, 2, 3, [10, 5])
7
8. CREATING TUPLES FOR SINGLE ITEM
>>>my_college=("SKSJTI")
>>> print(my_college)
SKSJTI
We have got our expected
output lets check its
type….
>>> type(my_college)
<class ‘str’>
What…! we got
string,we have not
missed parentheses right
then why not tuple?
>>>num=(1)
>>> type(num)
<class ‘int’>
A single value inside a
parentheses is not a
tuple
>>> x=(3)
>>> print (x)
3 ## not a tuple but
an integer
>>> type(x)
<class 'int'>
>>> x=(3,)
>>> print (x)
(3,)
>>> type (x)
<class 'tuple'> 8
9. Now lets alter the same program and check the output:
Now lets check its type:
>>>my_college2=(“SKSJTI”,)
>>> print(my_college2)
('SKSJTI',)
Youcan notice some
changesin the code and
outputofthe print
statementcomparedto
previousone
>>> type(my_college2)
<class ‘tuple’>
Yes..! we got it
as tuple
Final comma
CONCLUSION : To create a tuple with single element,you have to include the
final comma; otherwise python will not recognize the object as tuple.
9
10. • >>> min(t1)
• 'hello'
• >>> min(t)
• 'd'
Simple Operations with Tuples
Comparing tuples:
• Tuples can be compared using operatorslike >, == etc.
• When we need to check equality among two tuple objects,
the first item in first tuple is compared with first item in
second tuple. If they are same, next items are compared. The
check continues till either a mismatch is found or items get
over.
• Ex
>>> (1,2,3)>(1,2,5)
False
>>> (3,4)==(3,4)
True
>>> ('hi','hello') > ('Hi','hello')
True
>>>(1,2)<('h','k')
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
(1,2)<('h', 'k')
TypeError: '<' not supported between instances
of 'int' and 'str'
>>> t='Mango', 'Banana', 'Apple’
#without parentheses
>>> print(t)
('Mango', 'Banana', 'Apple’)
>>> t1=('Tom', 341, 'Jerry’)
#with parentheses
>>> print(t1)
('Tom', 341, 'Jerry’)
Note: Tuple is an
ordered (sequence)
data type. Its
elements can be
accessed using
positional index
10
11. • >>> t=(1,3,4,5, 5,6,7)
• >>> print (t)
• (1, 3,4,5,5, 6,7)
• >>> t.count(5)
• 2
• >>> print (t[3])
• 5
• >>> print (t[4])
• 5
Simple Operations with Tuples
## create a new tuple using existing tuples
(similar to string concatenation)
>>> t1=('C', 'Python')
>>> t2=('matlab',)
>>> t=t1+t2
>>> print (t)
('C', 'Python', 'matlab')
## strings vs tuples
t=("hello" "world")
>>> print (t)
helloworld
>>> type (t)
<class 'str'>
>>> t1=("hello", "world")
>>> print (t1)
('hello', 'world')
>>> type (t1)
<class 'tuple'>
>>>print (t[0])
h
>>> print (t1[0])
hello
>>>print (t[1])
e
>>>print (t1[1])
World
>>>print (t[2])
l
>>>print (t1[2])
Traceback (most recent call last):
File "<pyshell#79>", line 1, in
<module>
print (t1[2])
IndexError: tuple index out of
range
>>>max(t1)
'world'
>>> max(t)
'w'
>>> min(t1)
'hello'
>>> min(t)
'd'
>>> t=(1, 3, 4, 5, 5, 6, 7)
>>> print (t)
(1, 3, 4, 5, 5, 6, 7) ## supports duplicate elements
>>> print (t[3])
5
>>> print (t[4])
5
### different ways to define tuples
>>>tup1 = ('python’, ‘java', 2021, 98.6)
>>>tup2 = (1, 2, 3, 4, 5 )
>>>tup3 = "a", "b", "c", "d"
11
12. Slicing in Tuples
If you want to access a range of items in a tuple or you want a part(slice) of a tuple,
use slicing operator [ ] and colon :
>>> #positive indexing
>>> percentage = (90,91,92,93,94,95)
#Slicing
>>> percentage[2:4]
(92, 93)
>>> percentage[ :4]
(90, 91, 92, 93)
>>> percentage[4: ]
(94, 95)
>>> percentage[2:2]
()
>>> #Negative indexing
>>> percentage[ : − 2]
(90, 91, 92, 93)
>>> percentage[− 2: ]
(94, 95)
>>> percentage[2: − 2]
(92, 93)
>>> percentage[− 2:2]
()
>>> percentage[ : ] #Prints whole tuple
(90, 91, 92, 93, 94, 95)
>>> t=('Mango', 'Banana', 'Apple’)
>>> print(t[1])
Banana
>>> print(t[1:]) ## slicing
('Banana', 'Apple’)
>>> print(t[-1])
Apple ## slicing with negative index
12
13. TUPLE ASSIGNMENT
Tuple assignment feature allows a tuple of variables on the left side of an assignment
to get the values on the right side.
>>> a,b,c,d=‘apple’,‘mango’,‘grapes’,‘orange’
>>> print(a)
apple #output
>>> a,b,c,d=1,2,3,4
>>> print(c)
3 #output
>>> a,b,c,d=1,2,3
ValueError: not enough values to unpack
(expected 4, got 3)
The number of variables on the left and the
number of values on the right have to be same
>>> email = ‘monty@python.org’
>>> uname, domain = email.split('@’)
>>> print(uname ,‘n’, domain)
monty
python.org
The return value from split is a list with two
elements; the first element is assigned to
uname, the second to domain. 13
14. TUPLE ASSIGNMENT
###When we have list of items,
they can be extracted and stored
into multiple variables
>>>t1=("hello", "world")
>>> x, y=t1
>>> print (x)
hello
>>> print (y)
world
## x and y got the values
As per the index
The best known example of assignment
of tuples is swapping two values
(a,b)=(10,20)
>>> print (a,b)
10 20
>>> a,b=b,a
>>> print (a,b)
20 10
###
the statement a, b = b, a is treated by
Python as – LHS is a set of variables,
and RHS is set of expressions. The
expressions in RHS are evaluated and
assigned to respective variables at LHS
>>>(a,b)=(10,20,30)
Traceback (most recent call last):
File "<pyshell#88>", line 1, in
<module>
(a,b)=(10,20,30)
ValueError: too many values to unpack
(expected 2)
Note: While doing assignment of
multiple variables, the RHS can be
any type of data like list, string, tuple,
int etc.
>>> (a,b)=(20,'krishna')
>>> print (a,b)
20 krishna
14
15. Tuples As Return Values of a function
a=(12,34,55)
>>> min(a)
12
>>> min(a),max(a)
(12,55)
A function can only return one value, but if the value is a tuple, the effect is same as
returning multiple values.
>>> t = divmod(7,3)
‘‘‘ Built in function divmod takes two arguments
and returns two vales: quotient and remainder’’’
>>> t
#output
(2,1)
>>> quot , rem = divmod(7,3)
>>> quot
#output
2
>>> rem
1
t=(1,2,3,4)
def min_max(t):
return
min(t),max(t)
print(min_max(t))
#max and min are built-in function returns largest and
smallest number
#output
(1, 4)
a=(12,34,55)
>>> min(a)
12
>>> min(a), max(a)
(12, 55)
15
16. VARIABLE-LENGTH ARGUMENT TUPLES
Functions can take a variable number of arguments. A parameter name that begins with
* gathers (makes) arguments into a tuple.
Example : printall takes any number of arguments:
>>> def printall(*args):
print(args)
…..
>>> printall(1,2.0,'3')
(1, 2.0, '3')
The * gather parameter can have any name
you like, but args is conventional.
>>>def printall(*args):
print (args)
>>> printall (1,(4,5), 'krishna')
(1, (4, 5), 'krishna')
16
17. • SS
The complement of gather is scatter.
If you have a sequence of values and you want to pass it toa function as multiple
arguments, you can use * operator.
Example: divmod takes exactly two arguments; it doesn’t work with tuple.
>>> t=(7,3)
>>> divmod(t)
TypeError: divmod expected 2arguments, got 1
>>> divmod(*t)
(2,1)
But if you scatter the tuple it works:
Many built-in functions use variable length parameters except sum().
>>> max(1,2,3)
3
>>> sum(1,2,3)
TypeError: sum() takes at most 2 arguments (3 given)
17
19. 1. len()
Like a list, a python tuple is of a certain length. The len() function returns the number
of elements in the tuple.
>>>t=(1,'mango',2,'apple',3,'grapes')
>>> len(t)
6
>>>t1=(23, 45.67, 'krishna',[5,6])
>>>len(my_tuple)
4
2.max()
It returns the item from the tuple which is having a highest value.
>>> max(34.56, 78.34, 100.45)
100.45
>>>max(34.56,78.34,100.45, 200)
200
19
20. >>> no_s=(1,2,3,4,5,6)
>>> max(no_s)
6
>>> x=(1,2,3,4,[5,6])
>>> max(x)
Traceback (most recent call
last):
File "<pyshell#17>", line 1, in
<module>
max(x)
TypeError: '>' not supported
between instances of 'list' and
'int'
>>> y=( ‘Hi’, ‘hi’, ‘Hello’)
>>> max(y)
‘hi’
>>> a=('hi',9)
>>> max(a)
Traceback (most recent call
last):
File "<pyshell#19>", line 1, in
<module>
max(a)
TypeError: '>' not supported
between instances of 'int' and
'str'
Youcant compare int and list Youcant compare int and string
20
21. 3.min()
Like the max() function, the min() returns the item with lowest values.
>>> no_s=(10,20,30,40,50,60)
>>> min(no_s)
10
>>> x=('hi','Hi','Hello')
>>> min(x)
'Hello'
4.sum()
This function returns the arithmetic sum of all the items in the tuple.
>>> no_s=(1,2,3,4,5,6)
>>> sum(no_s)
21
>>> x=('1','2','3','4') >>> sum(x)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
sum(x)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Youcan’t apply this function on a tuple with strings.
>>> min(34.56, 78.34, 100.45, 200)
34.56
>>>sum(34.56,78.34,100.45,200)
Traceback(mostrecentcall last):
File "<pyshell#131>",line1, in <module>
sum(34.56,78.34,100.45,200)
TypeError:sum()takesat most 2 arguments(4given)
>>>sum("krishna","hello")
Traceback(mostrecentcall last):
File "<pyshell#135>",line1, in <module>
sum ("krishna","hello")
TypeError:sum()can't sum strings[use ''.join(seq)instead]
21
22. 5.any()
Python any() function returns true if any of the item in tuple is true else it returns false.
The any() function returns false if the passed tuple is empty.
# all elements are true
>>>t=(1,"Begginers",22)
>>>print(any(t))
True
>>>t=(1,2,3,4)
>>>print(any(t))
True
#emptytuple
>>> t=()
>>> print(any(t))
False
#all elementsare false
>>> t2=(0,False,0)
>>> print(any(t2))
False
22
23. 6. all()
Python all() function returns true if all the item in tuple is true else it returns false.
The all() function returns true if the passed tuple is empty.
The 0(zero) values are considered as false and non zero values such as 1,2,30…etc are
considered true
>>> t=(0,1,0,3)
>>> print(all(t))
False
>>> t=('abc',1,2,3)
>>> print(all(t))
True
>>> t=('abc',False,2,3)
>>> print(all(t))
False
>>> t=(True,0,False)
>>> print(all(t))
False
>>> t=() ## empty tuple
>>> print (all(t))
True
>>> t=(23, 1, 6)
>>> print (all(t))
True
>>> t=(0,0,0)
>>> print (all(t))
False
>>> t=(0,2,4)
>>> print (all(t))
False
23
24. 7. sorted()
This function returns a sorted version of the tuple.
The sorting is in ascending order, but you can specify ascending or descending and it
doesn’t modify the original tuple in python.
>>> a=(3,4,5,1,2,6)
>>> sorted(a)
# output
[1, 2, 3, 4, 5, 6]
a=('h','b','a','d','c','e','g','f')
y=sorted(a)
print(y)
#output
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
#descending order
a=('h','b','a','d','c','e','g','f')
y=sorted(a, reverse=True)
print(tuple (y))
#output
('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a')
>>> a=(45, 636, 23, 35.33, 89.34)
>>> sorted(a)
[23, 35.33, 45, 89.34, 636]
>>> print (sorted(a))
[23, 35.33, 45, 89.34, 636]
>>> print (sorted(a, reverse=True))
[636, 89.34, 45, 35.33, 23]
24
25. 8. tuple()
This function converts another construct into a python tuple.
list1=[1,2,3,4]
y=tuple(list1)
print(y)
#output
(1, 2, 3, 4)
str=“GovtSKSJTI"
y=tuple(str)
print(y)
#output
('G', 'o', 'v', ‘t', ‘S', ‘K', ‘S', ‘J, ‘T', ‘I')
set1={2,1,3}
y=tuple(set1)
print(y)
#output
{1, 2, 3}
We declared set as 2,1,3 it automatically reordered itself to
1,2,3.Furthermore, creating python tuple form it returned the
new tuple in the new order, that is ascending order
25
26. PYTHON TUPLE METHODS
A method is a sequence of instructions to perform some task.
We call a method using the dot operator in python.
Python has two built-in methods to use with tuples
1. index()
This method takes one argument and returns the index of the first appearance of an
item in a tuple.
>>> a=(1,2,3,2,4,5,2)
>>> a.index(2)
#output
1
>>> a.index(3)
2
As you can see, we have 2’s at positions 1, 3 and 6.
But it returns only first index
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of
first appearance of that element
26
27. 2. count()
This method takes one argument and returns the number of times an item
appears in the tuple.
>>> a=(1,2,3,2,4,5,2)
>>> a.count(2)
#output
3
As you can see, 2 is repeated three
times the output is 3
>>> t=(1,3,'a','a','a','krishna',3,5)
>>> print (t)
(1, 3, 'a', 'a', 'a', 'krishna', 3, 5)
>>> t.index('a')
2
>>> t.count('a')
3
>>> t.count(3)
2
>>>t.index('krishna')
5
27
28. Note: You can't add elements to
a tuple because of their
immutable property. There's
no append() or extend() method
for tuples
Note: We cant remove or replace
individual elements from the
tuple
28
29. PYTHON TUPLE OPERATIONS
1.Membership
We can apply the ‘in’ and ‘not in’ operators on items. This tells us whether they
belong to the tuple. t1=(1,2,3,4,5)
t2=(6,7,8,9)
for item in list1:
if item in list2:
print('overlapping')
else:
print('not overlapping’)
#output
not overlapping
>>> t=(1,3,'a','krishna',5)
>>> print (t)
(1, 3, 'a', 'krishna', 5)
>>> 3 in t
True
>>> 'a' in t
True
>>> 2 in t
False 29
30. 2. Concatenation
Concatenation is the act of joining. We can join two tuples using the
concatenation operator ‘+’.
x=(1,2,3)
y=(4,5,6)
z=x + y
print(z)
#output
(1, 2, 3, 4, 5, 6)
x=(1,2,3)
y=(‘Bengaluru’,)
z=x + y
print(z)
#output
(1, 2, 3, ‘Bengaluru')
3. Relational All Relational operators (like >,>=,…) can be applied on a tuple.
>>> (1,2,3) > (4,5,6)
False
>>> (1,2)==(‘1’,‘2’)
False
int 1 and 2 aren’t equal to the strings ‘1’ and ‘2’ so it returned.
Tuples are comparable.
>>> x=('java',‘ python')
>>> y=('C', 'C++', 'Ruby')
>>> print (x+y)
('java', 'python', 'C', 'C++', 'Ruby')
30
31. 4. Identity()
• Identity operators are used to determine whether a value is of a certain class or
type.
• They are usually used to determine the type of data a certain variable contains.
• There are two identity operators: ‘is’ and ‘is not’
x=(1,2,3,4,5)
if ( type(x) is tuple):
print(‘true')
else:
print(‘false’)
#output
true
x=(1,2,3,4,5)
if ( type(x) is not list):
print(‘true')
else:
print(‘false’)
#output
true
>>> x=(1,2,3,4,5)
>>> (1,2,3,4,5) is x
#output
false
31
32. The Python is and is not operators compare
the identity of two objects.
Everything in Python is an object, and each
object is stored at a specific memory location.
The Python is and is not operators check
whether two variables refer to the same object
in memory.
'is' operator – Evaluates to true if the variables
on either side of the operator point to the
same object and false
'is not' operator – Evaluates to false if the
variables on either side of the operator point
to the same object and true otherwise.
They are used to check if two values (or
variables) are located on the same part of the
memory. Two variables that are equal
does not imply that they are identical.
b=(4,5,6)
>>> y=('C', 'C++', 'Ruby')
>>> b is y
False
>>> b is not y
True
>>> a=(1,2,3)
>>> id(a)
1956981818624
>>> b=(1,2,3)
>>> id(b)
1956981816768
>>> a is b
False
>>> a==b
True
## deleting a tuple
>>> y=('C', 'C++', 'Ruby')
>>> print (y)
('C', 'C++', 'Ruby')
>>> id (y)
1956981813440
>>> del y
>>> print (y)
Traceback (most recent call last):
File "<pyshell#218>", line 1, in
<module>
print (y)
NameError: name 'y' is not defined
32
33. We can iterate on a python tuple using a for loop ,its similar as we iterate on a
list
for i in (1,2,3):
print(i)
#output
1
2
3
s='abc'
t=(1,2,3)
for pair in zip(s,t):
print(pair)
#output
('a', 1)
('b', 2)
('c', 3)
zip is a built in function that takes two
or more sequences and returns a list of
tuples where each tuple contains one
element from each sequence.
Here 'abc' is a string and (1,2,3) is a
tuple
#You can use zip object to make a list
>>> list(zip(s, t))
[('a', 0), ('b', 1), ('c', 2)]
Iterating on Python tuples
>>> list(zip('Anne', 'Elk’))
#Sequence lengths are not same
[('A', 'E'), ('n','l'), ('n', 'k')] 33
34. t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print(number, letter)
#output
0 a
1 b
2 c
Each timethrough the loop,
Python selects the next tuple
in the list and assigns the
elementsto letterand number.
Let us try to get the output of the elements of a sequence with
their indices . Using built in function enumerate:
for index, element in enumerate('abc'):
print(index, element)
#output
0 a
1 b
2 c
34
35. DICTIONARIES AND TUPLES
Dictionaries have a method called items that returns a sequence of tuples, where each
tuple is a key value pair:
>>> d={'a':0, 'b':1, 'c':2 }
>>> t=d.items()
>>> t
dict_items([('a',0), ('b', 1), ('c', 2)])
The result is a dict_items object , which
is an iterator that iterates the key value
pairs.
You can use it is a for loop like this:
>>> for key,value in d.items():
… print(key,value)
…
a 0
b 1
c 2
35
36. You can also use a list of tuples to initialize a new dictionary:
>>> t= [('a', 0), ('b', 1), ('c', 2)]
>>> d= dict(t)
>>> d
{'a':0, 'b':1, 'c':2 }
Combining dict with zip yields a concise way to create a
dictionary.
>>> d= dict(zip(‘abc’,range(3)))
>>> d
{'a':0,'c’:2,'b':1}
36