Tuesday, January 12, 2021

Python Set

 

Python’s built-in set type has the following characteristics:

Sets are unordered.

Set elements are unique. Duplicate elements are not allowed.

A set itself may be modified, but the elements contained in the set must be of an immutable type.

A set can be created in two ways. First, you can define a set with the built-in set() function:


myset = {"Assam", "Banaras", "Chennai"}


Check if "Banaras" is present in a set:

myset = {"Assam", "Banaras", "Cherry"}

print("Banaras" in myset)

Output would be true


Using add () method, we can add an element to the set.

myset = {"Apple","Banaras","Chennai"}

myset.add("orange")


To add items from another set into the current set, use the update() method.

Add elements from secondset and myset into newset:

myset = {"Apple","Banaras","Chennai"}

secondset = {"Patna", "Mangalore", "Pune"}

myset.update(secondset)


Removing elements from set

There are two methods to remove an element from set.

remove () and discard(). Both the methods takes the element to be removed as argument. If the element is not present, remove method will flag an error while discard won't.

The clear() method empties the set:

myset = {"Assam", "Banaras", "Chennai"}

myset.clear()


The del keyword will delete the set completely

myset = {"Assam", "Banaras", "Chennai"}

del myset

pop() method removes an element, the last element from a set. Since set is unordered, we can't say which element will be removed.which element is last one 

myset = {"Assam", "Banaras", "Chennai"}

x = myset.pop()



No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner