Sets in Python

sets are similar to lists but it dosent support indexing,you can store elemnts randomly ,no prticular order ,sets are enclosed by curly brackets { }

setx = { element1, element 2, element 3 ..., element N }

example:

x={2,5,56,6,645,645}

set() constructor function can be used to create sets,lets see one example converting a list to set

namex =set(["alex","john","lilly"])
{'alex', 'john', 'lilly'}

Adding and removing elements

we can use add( ) and remove ( ) operator .for adding and removing elemnts in the sets

namex.add("rosey")
{'alex', 'john', 'lilly', 'rosey'}
namex.remove("john")
{'alex', 'lilly', 'rosey'}

replacing an element

we can replace any element using update( ) method

namex.update(["alex","tom"])
{'tom', 'lilly', 'rosey'}

deleting all elements in the set,we can use clear( ) method

namex.clear( ) #deletes all elements
Last updated on by vishal devxo