Set in Python is an unordered collection of unique elements.

Here unique elements mean that set maintains only a single copy of every element. It removes other copies of the same element even if you try to do so.

Python Set Syntax:-

Let’s see some example of sets in python.

Create Set & Add Item

A set in python can be created using { } or set() function.



Access Set item

Since the set is unordered so we cannot access the element directly using its index value. But we can iterate through set using for loop.


Update Set item

Once a set is created it any of its items can not be changed or updated but we can add a new item to the set.

Remove Set item

To remove an item from the set we use pop() method but it is not guaranteed which element will be removed because the set is unordered.


Basic Set Methods

Use: set_name.method_name()

  • add() – Add new element to the set.
  • clear() – Removeas all elements from the set.
  • copy() – Returns the copy of set.
  • difference(set2) – Return the diference of current set with set2 in the form of a set.
  • discard(x) – Removes x from the set.
  • pop() – Removes a random element from the list.
  • update(set2) – Combine elements of set2 with current set.
  • union(set2) – Returns a set which contains all elements from

Python Examples using methods on set:





Comment all your doubts and suggestion.

Leave a Reply

seventeen + thirteen =