3. Tuple in Python
• In python, a tuple is a sequence of immutable elements or items.
• Tuple is similar to list since the items stored in the list can be
changed whereas the tuple is immutable and the items stored in
the tuple cannot be changed.
• A tuple can be written as the collection of comma-separated
values enclosed with the small brackets ( ).
Syntax: var = ( value1, value2, value3,…. )
Example: “tupledemo.py”
t1 = ()
t2 = (123,"python", 3.7)
t3 = (1, 2, 3, 4, 5, 6)
t4 = ("C",)
print(t1)
print(t2)
print(t3)
print(t4)
Output:
python tupledemo.py
()
(123, 'python', 3.7)
(1, 2, 3, 4, 5, 6)
('C',)
5. Tuple Indexing in Python
• Like list sequence, the indexing of the python tuple starts from
0, i.e. the first element of the tuple is stored at the 0th index,
the second element of the tuple is stored at the 1st index, and
so on.
• The elements of the tuple can be accessed by using the slice
operator [].
Example:
mytuple=(‘banana’,’apple’,’mango’,’tomato’,’berry’)
• mytuple[0]=”banana” mytuple[1:3]=[”apple”,”mango”]
• mytuple[2]=”mango”
6. Tuple Indexing in Python cont…
• Unlike other languages, python provides us the flexibility to use
the negative indexing also. The negative indices are counted
from the right.
• The last element (right most) of the tuple has the index -1, its
adjacent left element is present at the index -2 and so on until
the left most element is encountered.
Example: mytuple=[‘banana’,’apple’,’mango’,’tomato’,’berry’]
• mytuple[-1]=”berry” mytuple[-4:-2]=[“apple”,mango”]
• mytuple[-3]=”mango”
8. Tuple Operators in Python
+
It is known as concatenation operator used to concatenate two
tuples.
*
It is known as repetition operator. It concatenates the multiple
copies of the same tuple.
[]
It is known as slice operator. It is used to access the item from
tuple.
[:]
It is known as range slice operator. It is used to access the range
of items from tuple.
in
It is known as membership operator. It returns if a particular
item is present in the specified tuple.
not in
It is also a membership operator and It returns true if a
particular item is not present in the tuple.
9. Tuple Operators in Python cont…
Example: “tupleopdemo.py”
num=(1,2,3,4,5)
lang=('python','c','java','php')
print(num + lang) #concatenates two tuples
print(num * 2) #concatenates same tuple 2 times
print(lang[2]) # prints 2nd index value
print(lang[1:4]) #prints values from 1st to 3rd index.
print('cpp' in lang) # prints False
print(6 not in num) # prints True
Output: python tupleopdemo.py
(1, 2, 3, 4, 5, 'python', 'c', 'java', 'php')
(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
java
('c', 'java', 'php')
False
True
10. How to add or remove elements from a tuple?
• Unlike lists, the tuple items cannot be updated or deleted as
tuples are immutable.
• To delete an entire tuple, we can use the del keyword with the
tuple name.
Example: “tupledemo1.py”
tup=('python','c','java','php')
tup[3]="html"
print(tup)
del tup[3]
print(tup)
del tup
Output:
python tupledemo1.py
'tuple' object does not
support item assignment
'tuple' object doesn't
support item deletion
11. Traversing of tuples
• A tuple can be iterated by using a for - in loop. A simple tuple
containing four strings can be iterated as follows..
Example: “tupledemo2.py”
lang=('python','c','java','php')
print("The tuple items are n")
for i in lang:
print(i)
Output:
python tupledemo2.py
The tuple items are
python
c
java
php
13. Tuples Functions in Python
• Python provides various in-built functions which can be used
with tuples. Those are
☞ len():
• In Python, len() function is used to find the length of tuple,i.e it
returns the number of items in the tuple.
Syntax: len(tuple)
• len()
• sum()
Example: lendemo.py
num=(1,2,3,4,5,6)
print("length of tuple :",len(num))
Output:
python lendemo.py
length of tuple : 6
• tuple()
•sorted()
14. Tuple Functions in Python Cont..
☞ sum ():
• In python, sum() function returns sum of all values in the tuple. The
tuple values must in number type.
Syntax: sum(tuple)
Example: sumdemo.py
t1=(1,2,3,4,5,6)
print("Sum of tuple items :",sum(t1))
Output:
python sumdemo.py
Sum of tuple items : 21
15. Tuple Functions in Python Cont..
☞ sorted ():
• In python, The sorted() function returns a sorted copy of the tuple
as a list while leaving the original tuple untouched.
• .
Syntax: sorted(tuple)
Example: sorteddemo.py
num=(1,3,2,4,6,5)
lang=('java','c','python','cpp')
print(sorted(num))
print(sorted(lang))
Output:
[1, 2, 3, 4, 5, 6]
['c', 'cpp', 'java', 'python‘]
16. Tuple Functions in Python Cont..
☞ tuple ():
• In python, tuple() is used to convert given sequence (string or list)
into tuple.
Syntax: tuple(sequence)
Example: tupledemo.py
str="python"
t1=tuple(str)
print(t1)
num=[1,2,3,4,5,6]
t2=tuple(num)
print(t2)
Output:
python tupledemo.py
('p', 'y', 't', 'h', 'o', 'n‘)
(1, 2, 3, 4, 5, 6)
17. Tuple Functions in Python Cont..
☞ tuple ():
• In python, tuple() is used to convert given sequence (string or list)
into tuple.
Syntax: tuple(sequence)
Example: tupledemo.py
str="python"
t1=tuple(str)
print(t1)
num=[1,2,3,4,5,6]
t2=tuple(num)
print(t2)
Output:
python tupledemo.py
('p', 'y', 't', 'h', 'o', 'n‘)
(1, 2, 3, 4, 5, 6)
18. Tuple Methods in Python Cont..
☞ count():
• In python, count() method returns the number of times an element
appears in the tuple. If the element is not present in the tuple, it
returns 0.
Syntax: tuple.count(item)
Example: countdemo.py
num=(1,2,3,4,3,2,2,1,4,5,8)
cnt=num.count(2)
print("Count of 2 is:",cnt)
cnt=num.count(10)
print("Count of 10 is:",cnt) Output:
python countdemo.py
Count of 2 is: 3
Count of 10 is: 0
19. Tuple Methods in Python Cont..
☞ index():
• In python, index () method returns index of the passed element. If
the element is not present, it raises a ValueError.
• If tuple contains duplicate elements, it returns index of first
occurred element.
• This method takes two more optional parameters start and end
which are used to search index within a limit.
Syntax: tuple.index(item [, start[, end]])
Example: indexdemo.py
t1=('p','y','t','o','n','p')
print(t1.index('t'))
Print(t1.index('p'))
Print(t1.index('p',3,10))
Print(t1.index('z')) )
Output:
python indexdemo.py
2
0
5
Value Error
20. Relation between Tuples and Lists
• Tuples are immutable, and usually, contain a heterogeneous
sequence of elements that are accessed via unpacking or
indexing.
• Lists are mutable, and their items are accessed via indexing.
• Items cannot be added, removed or replaced in a tuple.
• Ex:
• tuple=(10,20,30,40,50)
• tuple[0]=15
• Traceback (most recent call last):
• File "<pyshell#5>", line 1, in <module>
• tuple[0]=15
• TypeError: 'tuple' object does not support item assignment
21. Relation between Tuples and Lists
• Convert tuple to list:
• tuple_to_list=list(tuple)
• print(tuple_to_list)
• [10, 20, 30, 40, 50]
• If an item within a tuple is mutable, then you can change it.
Consider the presence of a list as an item in a tuple, then any
changes to the list get reflected on the overall items in the
tuple. For example,
23. Relation between Tuples and dictionaries
• Tuples can be used as key:value pairs to build dictionaries. For
example,
• num=(("one",1),("two",2),("three",3))
• tuple_to_dict=dict(num)
• print(tuple_to_dict)
• {'one': 1, 'two': 2, 'three': 3}
• num
• (('one', 1), ('two', 2), ('three', 3))
• The tuples can be converted to dictionaries by passing the tuple
name to the dict() function. This is achieved by nesting tuples
within tuples, wherein each nested tuple item should have two
items in it .
• The first item becomes the key and second item as its value when
• the tuple gets converted to a dictionary
24. • The method items() in a dictionary returns a list of tuples
where each tuple corresponds to a key:value pair of the
dictionary. For example,
• dict1={"y":"yellow","o":"orange","b":"blue"}
• dict1.items()
• dict_items([('y', 'yellow'), ('o', 'orange'), ('b', 'blue')])
• for symbol,colour in dict1.items():
• print(symbol," ",colour)
Output:
• y yellow
• o orange
• b blue
25. • Tuple packing and unpacking:
The statement t = 12345, 54321, 'hello!' is an example of tuple packing.
t=12345,54321,'hello!'
t
(12345, 54321, 'hello!')
The values 12345, 54321 and 'hello!' are packed together into a tuple.
The reverse operation of tuple packing is also possible. For example,
tuple unpacking
x,y,z=t
x
12345
y
54321
z
'hello!‘
Tuple unpacking requires that there are as many variables on the left side of the
equals sign as there are items in the tuple.
Note that multiple assignments are really just a combination of tuple packing and
unpacking.
26. • Populating tuples with items:
• You can populate tuples with items using += operator and also by
converting list items to tuple items.
• Example:
tuple_items=()
tuple_items+=(10,)
tuple_items+=(20,30,)
print(tuple_items)
(10, 20, 30)
• converting list to tuple :
list_items=[]
list_items.append(50)
list_items.append(60)
list_items
[50, 60]
tuple1=tuple(list_items)
print(tuple1)
(50, 60)
27. • Using zip() Function
• The zip() function makes a sequence that aggregates elements from each
of the iterables (can be zero or more). The syntax for zip() function is,
• zip(*iterables)
• An iterable can be a list, string, or dictionary.
• It returns a sequence of tuples, where the i-th tuple contains the i-th
element from each of the iterables.
For Example,
x=[1,2,3]
y=[4,5,6]
zipped=zip(x,y)
list(zipped)
[(1, 4), (2, 5), (3, 6)]
Here zip() function is used to zip two iterables of list type
28. To loop over two or more sequences at the same time, the
entries can be paired with the zip() function. For
example,
symbol=("y","o","b","r")
colour=("yellow","orange","blue","red")
for symbol,colour in zip(symbol,colour):
print(symbol," ",colour)
Output:
y yellow
o orange
b blue
r red
Since zip() function returns a tuple, you can use a for loop
with multiple iterating variables to print tuple items.
29. • SETS:
• A set is an unordered collection with no dupli- cate items.
• Sets also support mathematical operations, such as union,
intersection, difference, and symmetric difference.
• Curly braces { } or the set() function can be used to create sets with
a comma-separated list of items inside curly brackets { }.
• To create an empty set you have to use set() and not { } as the
latter creates an empty dictionary.
• Set operations:
• Example:
• basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
• >>> print(basket)
• {'pear', 'orange', 'banana', 'apple'}
• >>> 'orange' in basket
• True
• >>> 'crabgrass' in basket
• False
30. Difference:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}
a-b
{'r', 's', 'd', 'b'}
It Displays letters present in a, but not in b, are printed.
Union:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}
a|b
{'b', 'z', 'c', 'a', 'r', 'd', 'm', 'l', 's'}
Letters present in set a and set b are printed.
31. Intersection:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}
a&b
{'c', 'a'}
Letters present in both set a and set b are printed
Symmetric Difference:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}
a^b
{'z', 'b', 'r', 'd', 'm', 'l', 's'}
Letters present in set a or set b, but not both are printed.
33. Set Methods:
You can get a list of all the methods associated with the set by passing the set
function to dir().
dir(set)
['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getstate__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__',
'__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__',
'__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__',
'__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__',
'__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy',
'difference', 'difference_update', 'discard', 'intersection',
'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove',
'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
34. Set Methods:
Add():
The add() method adds an item to the set set_name.
Syntax: set_name.clear()
basket={"orange","Apple","strawberry","orange" }
basket
{'orange', 'Apple', 'strawberry'}
basket.add("pear")
basket
{'orange', 'Apple', 'strawberry', 'pear'}
35. Set Methods:
Difference:
• The difference() method returns a new set with items in the set set_name that
are not in the others sets.
• Syntax : set_name.difference(*others)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.difference(flowers)
{'orchid', 'daisies'}
intersection():
• The intersection() method returns a new set with items common to the set
set_name and all others sets.
• Syntax: set_name. Intersection(*others)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.intersection(flowers)
{'roses', 'tulips'}
36. Set Methods:
Symmetric Difference:
The method symmetric difference() returns a new set with items in either
the set or other but not both.
• Syntax : set_name. symmetric_difference(other)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers. symmetric_difference (flowers)
{'orchid', 'lilies', 'daisies', 'sunflowers'}
Union:
• The method union() returns a new set with items from
• the set set_name and all others sets.
• Syntax: set_name.union(*others)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.union(flowers)
{'orchid', 'lilies', 'tulips', 'daisies', 'roses', 'sunflowers'}
37. Set Methods:
isdisjoint:
• The isdisjoint() method returns True if the set set_name has no items in
common with other set. Sets are disjoint if and only if their intersection is
the empty set.
• Syntax : set_name.isdisjoint(other)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.isdisjoint(flowers)
False
a= {'b', 'c', 'a', 'd'}
b={'f', 'g', 'h', 'e'}
a.isdisjoint(b)
True
38. Set Methods:
issubset:
• The issubset() method returns True if every item in the set
• set_name is in other set.
• Syntax : set_name.issubset(other)
Ex:
a={'b', 'c', 'a', 'd'}
b={'f', 'g', 'h', 'e'}
a.issubset(b)
False
c={"a","b","c","d"}
d={"a","b","c","d"}
c.issubset(d)
True
39. Set Methods:
Issuperset():
• The issuperset() method returns True if every element in other set is in the
set set_name.
• Syntax : set_name.issuperset(other)
Ex:
a={'b', 'c', 'a', 'd'}
b={'f', 'g', 'h', 'e'}
a.issubset(b)
False
c={"a","b","c","d"}
d={"a","b","c","d"}
c.issubset(d)
True
40. Set Methods:
Pop():
• The method pop() removes and returns an arbitrary item from
the set set_name. It raises KeyError if the set is empty.
• Syntax : set_name.pop()
Ex:
d={'b', 'c', 'a', 'd'}
item=d.pop()
print(item)
b
print(d)
{'c', 'a', 'd'}
41. Set Methods:
remove():
• The method remove() removes an item from the set set_name. It raises
KeyError if the item is not contained in the set.
• Syntax : set_name.remove(item)
• Ex:
• c={"a","b","c","d"}
c.remove("a")
print(c)
{'b', 'c', 'd'}
update():
• Update the set set_name by adding items from all others sets.
Syntax : set_name.update(*others)
Ex:
c={'b', 'c', 'd'}
d={"e","f","g"}
c.update(d)
print(c)
{'b', 'c', 'f', 'g', 'd', 'e'}
42. Set Methods:
Discard():
• The discard() method removes an item from the set set_name if it is present.
Syntax: set_name.discard(item)
Ex:
d={"e","f","g"}
d.discard("e")
print(d)
{'f', 'g'}
Clear():
• The clear() method removes all the items from the set set_name.
• Syntax: set_name.clear()
• Ex:
alpha={"a","b","c","d"}
print(alpha)
{'a', 'b', 'c', 'd'}
alpha.clear()
print(alpha)
set()
43. Traversing of sets
You can iterate through each item in a set using a for loop.
Ex:
alpha={"a","b","c","d"}
print(alpha)
{'a', 'b', 'c', 'd'}
for i in alpha:
print(i)
Output:
a
b
c
d
44. Frozenset
• A frozenset is basically the same as a set, except that it is
immutable. Once a frozenset is created, then its items cannot be
changed.
• The frozensets have the same functions as normal sets, except none
of the functions that change the contents (update, remove, pop,
etc.) are available.
methods in Frozenset:
1. >>> dir(frozenset)
[' and ', ' class ', ' contains ', ' delattr ', ' dir ', ' doc ', ' eq
', ' format ', ' ge ', ' getattribute ', ' gt ', ' hash ', ' init ', '
init_ subclass ', ' iter ', ' le ', ' len ', ' lt ', ' ne ', ' new ', ' or
', ' rand ', '__reduce ', ' reduce_ex ', ' repr ', ' ror ', ' rsub
', ' rxor ', ' setattr__', ' sizeof ', ' str ', ' sub ', ' subclasshook ', '
xor ', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset',
'issuperset', 'symmetric_difference', 'union']
45. Frozenset Methods
• List of methods available for frozenset .For example,
Convert set to frozenset
• fs=frozenset({"d","o","g"})
• print(fs)
• frozenset({'d', 'o', 'g'})
Convert list to frozenset:
• list=[10,20,30]
• lfs=frozenset(list)
• print(lfs)
• frozenset({10, 20, 30})
Convert dict to frozenset
dict1={"one":1,"two":2,"three":3,"four":4}
dfs=frozenset(dict1)
print(dfs)
frozenset({'four', 'one', 'three', 'two'})
46. • frozenset used as a key in dictionary and item in set:
item=frozenset(["g"])
dict1={"a":95,"b":96,"c":97,item:6}
print(dict1)
{'a': 95, 'b': 96, 'c': 97, frozenset({'g'}): 6}
EX:
item=frozenset(["g"])
set={"a","b","c",item}
print(set)
{frozenset({'g'}), 'a', 'c', 'b'}