0% found this document useful (0 votes)
4 views

Python sets

Uploaded by

gagotiasushant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python sets

Uploaded by

gagotiasushant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Python Training

Python Sets

- Aafiya Noorian Khan


Sets
• Set is a Collection which is unordered and unindexed.

• In python sets are written using { }.

• Access Items in Sets :


Set items cannot be accessed by referring to an index, since sets are
unordered item has no index.

• Once a set is created we cannot change, only add items to set.

• Set does not allow multiple elements/duplicates

• Sets does not support indexing ,slicing and repetition.


Creating a Set
A Set is written using {}

s={1,2,3,’abc’}
print(s)
Add and Remove Items/elements in a set.

add() – once a set is created we can only add items to the set.

update() – it is used to add multiple items to a set. It will not guarantee any order ,elements
can be added in any place in set.

len() - it is used get the number of items in set.

remove() – It is used to remove element in a set

discard() – It is used to remove element in a set.


pop() – it is used to remove the last element as sets are unordered we will not
know what item will be removed .The return value of pop() is removed.

clear() - it is used to clear the empty set

del () - deletes the set completely


Join two sets

union() - it returns new set containing all items from both sets.

update() - inserts all items from one set to another

Both union() and update() will exclude duplicate elements.


Set methods
copy() – Returns a copy of set

difference() – Returns a set containing difference between two or more sets.

subset() – A set which is build out of superset is known a subset.

superset () – Return whether this set containsanother set or not.

intersection() – Returns a set, that is the intersection of two other sets.


Frozen Set
• When a set is converted into Frozen set, update and remove operations cannot be
performed on set.

• frozenset is the keyword that is used to convert a set into frozenset.

You might also like