SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Downloaden Sie, um offline zu lesen
Tuple in Python
Tuple Creation
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',)
Tuple Indexing
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”
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”
Tuple Operators
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.
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
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
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
Built in functions used on tuples
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()
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
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‘]
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)
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)
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
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
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
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,
Relation between Tuples and Lists
• lang=["c","c++","java","python"]
• tuple=(10,20,30,40,50,lang)
• Print(tuple)
• (10, 20, 30, 40, 50, ['c', 'c++', 'java', 'python'])
• lang.append("php")
• lang
• ['c', 'c++', 'java', 'python', 'php']
• tuple
• (10, 20, 30, 40, 50, ['c', 'c++', 'java', 'python', 'php'])
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
• 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
• 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.
• 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)
• 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
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.
• 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
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.
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.
Length function():
basket={'apple','orange','apple','pear','apple','banana'}
print(basket)
{'pear', 'apple', 'orange', 'banana'}
len(basket)
4
Total number of items in the set basket is found using the len()
function
Sorted function():
sorted(basket)
['apple', 'banana', 'orange', 'pear']
The sorted() function returns a new sorted list from items in the
set .
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']
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'}
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'}
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'}
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
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
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
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'}
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'}
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()
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
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']
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'})
• 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'}

Weitere ähnliche Inhalte

Ähnlich wie updated_tuple_in_python.pdf

Ähnlich wie updated_tuple_in_python.pdf (20)

STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
 
Pytho_tuples
Pytho_tuplesPytho_tuples
Pytho_tuples
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Python standard data types
Python standard data typesPython standard data types
Python standard data types
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
PYTHON.pptx
PYTHON.pptxPYTHON.pptx
PYTHON.pptx
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Datatypes in Python.pdf
Datatypes in Python.pdfDatatypes in Python.pdf
Datatypes in Python.pdf
 
Core Concept_Python.pptx
Core Concept_Python.pptxCore Concept_Python.pptx
Core Concept_Python.pptx
 
Python data type
Python data typePython data type
Python data type
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Data types in python
Data types in pythonData types in python
Data types in python
 
02 Python Data Structure.pptx
02 Python Data Structure.pptx02 Python Data Structure.pptx
02 Python Data Structure.pptx
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)
 

Mehr von Koteswari Kasireddy

Chapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfChapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfKoteswari Kasireddy
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfKoteswari Kasireddy
 
Relational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxRelational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxKoteswari Kasireddy
 
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxUnit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxKoteswari Kasireddy
 
Database System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxDatabase System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxKoteswari Kasireddy
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptxKoteswari Kasireddy
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxKoteswari Kasireddy
 

Mehr von Koteswari Kasireddy (20)

DA Syllabus outline (2).pptx
DA Syllabus outline (2).pptxDA Syllabus outline (2).pptx
DA Syllabus outline (2).pptx
 
Chapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfChapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdf
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
 
unit-3_Chapter1_RDRA.pdf
unit-3_Chapter1_RDRA.pdfunit-3_Chapter1_RDRA.pdf
unit-3_Chapter1_RDRA.pdf
 
DBMS_UNIT_1.pdf
DBMS_UNIT_1.pdfDBMS_UNIT_1.pdf
DBMS_UNIT_1.pdf
 
business analytics
business analyticsbusiness analytics
business analytics
 
Relational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxRelational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptx
 
CHAPTER -12 it.pptx
CHAPTER -12 it.pptxCHAPTER -12 it.pptx
CHAPTER -12 it.pptx
 
WEB_DATABASE_chapter_4.pptx
WEB_DATABASE_chapter_4.pptxWEB_DATABASE_chapter_4.pptx
WEB_DATABASE_chapter_4.pptx
 
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxUnit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
 
Database System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxDatabase System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptx
 
Evolution Of WEB_students.pptx
Evolution Of WEB_students.pptxEvolution Of WEB_students.pptx
Evolution Of WEB_students.pptx
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Algorithm.pptx
Algorithm.pptxAlgorithm.pptx
Algorithm.pptx
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptx
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptx
 
linked_list.pptx
linked_list.pptxlinked_list.pptx
linked_list.pptx
 
matrices_and_loops.pptx
matrices_and_loops.pptxmatrices_and_loops.pptx
matrices_and_loops.pptx
 
algorithms_in_linkedlist.pptx
algorithms_in_linkedlist.pptxalgorithms_in_linkedlist.pptx
algorithms_in_linkedlist.pptx
 

Kürzlich hochgeladen

KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLManishPatel169454
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdfSuman Jyoti
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 

Kürzlich hochgeladen (20)

KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 

updated_tuple_in_python.pdf

  • 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
  • 12. Built in functions used on tuples
  • 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,
  • 22. Relation between Tuples and Lists • lang=["c","c++","java","python"] • tuple=(10,20,30,40,50,lang) • Print(tuple) • (10, 20, 30, 40, 50, ['c', 'c++', 'java', 'python']) • lang.append("php") • lang • ['c', 'c++', 'java', 'python', 'php'] • tuple • (10, 20, 30, 40, 50, ['c', 'c++', 'java', 'python', 'php'])
  • 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.
  • 32. Length function(): basket={'apple','orange','apple','pear','apple','banana'} print(basket) {'pear', 'apple', 'orange', 'banana'} len(basket) 4 Total number of items in the set basket is found using the len() function Sorted function(): sorted(basket) ['apple', 'banana', 'orange', 'pear'] The sorted() function returns a new sorted list from items in the set .
  • 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'}