Python Sets

A Set is a collection of items. Sets are unordered that means you cannot be sure how the order of a set will be appeared. Set items also cannot be changed. Sets are used with curly brackets. For example:

  1. set1 = {"c", "python", "java", "javascript"}

Accessing Set Items

You cannot access the set items by referring to the index number. As it is unordered it has no index. you can use a for loop to access the items.

Example:

  1. set1 = {"c", "python", "java", "javascript"}
  2. for x in set1:
  3. print(x)

Output:

c
java
javascript
python

Adding Items

You cannot change an item in a set but you can add new items using the add() method.

Example:

  1. set1 = {"c", "python", "java", "javascript"}
  2. set1.add("c++")
  3. print(set1)

Output:

{'c++', 'java', 'c', 'javascript', 'python'}

If you want to add more than one item to a set you should use the update() method.

Example:

  1. set1 = {"c", "python", "javascript"}
  2. set1.update(["c++", "java", "PHP"])
  3. print(set1)

Output:

{'python', 'java', 'PHP', 'c++', 'javascript', 'c'}

Removing Items

You can remove a specified item by using remove() or discard() method. Difference between these two methods that if the item you want to remove does not exist then the remove() method will raise an error but the discard() method does not.

Example:

  1. set1 = {"c", "python", "java", "javascript"}
  2. set1.remove("javascript")
  3. print(set1)

Output:

{'python', 'java', 'c'}

You can also use the clear() method, which empties the set.

Example:

  1. set1 = {"c", "python", "java", "javascript"}
  2. set1.clear()
  3. print(set1)

Output:

set()

The del statement will delete the set completely.

Example:

  1. set1 = {"c", "python", "java", "javascript"}
  2. del set1
  3. print(set1)

Output:

Traceback (most recent call last):
  File "C:\Users\Hp\Desktop\py\python.py", line 3, in <module>
    print(set1)
NameError: name 'set1' is not defined

Note: Since the total set is deleted an error is raised in the output.


Length of a Set

You can define the length of a set using the len() method.

Example:

  1. set1 = {"c", "python", "java", "javascript"}
  2. print(len(set1))

Output:

4

Set Methods

There are a set of built-in methods in python which you can use on sets.

Method Description
add() Inserts a item to the set
clear() Removes all the values from the set
copy() Returns a copy of the set
difference() Returns a set which contains the diiference between multiple sets
extend() Adds the items of a list with the current list
discard() Deletes the specified item from a set
intersection() Returns a set which is the intersection of sets
pop() Removes a value at any position from the set
remove() Removes the specified value from the set
union() Returns a set which contains the union of sets
update() Update the current set with the union of the sets