Set

  • A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements.
  • A set is a collection which is both unordered and unindexed.
  • Sets are written with curly brackets.

Create

  • The set can be created by enclosing the comma-separated items with the curly braces {}.
  • Python also provides the set() method, which can be used to create the set by the passed sequence.
  • But mutable elements (list, dictionary, set) can’t be a member of set.
myset = {"revin", "reviving", 54, 54.36}

print(myset)

x = set([1,2,3,4])

print(x,type(x))

Empty Set

  • Creating an empty set is a bit different because empty curly {} braces are also used to create a dictionary as well.
  • So Python provides the set() method used without an argument to create an empty set.
# Empty set using set() function  

myset = set()  

print(type(myset))  

Access

In set we can’t access using index or key only we can loop to get the elements or items of set.

myset = {"revin", "reviving", 54, 54.36}

for var in myset:

  print(myset)

Add or Change

  • We cannot change its items, but you can add new items.
  • We can add new items with add() & update() method

To add one item to a set use the add() method.

myset.add(“hello world")

print(myset)

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

myset1 = {"revin", "reviving", 54, 54.36}

myset2 = {1, 2}

myset1.update(myset2)

Note : update method can take any iterable object 

Remove

To remove an item in a set, use following methods:

  • remove
  • discared
  • pop
  • clear
  • del

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *