Sets

A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.

1. CREATE A SET IN PYTHON

thisset = {"apple", "banana", "cherry"}
print(thisset)

OUTPUT:

CREATE SET IN PYTHON
OUTPUT – CREATE SET IN PYTHON

2. ACCESS ITEMS OF SET IN PYTHON

You cannot access items in a set by referring to an index, since sets are unordered the items has no index.

2.1 ITERATE (loop) THROUGH A SET IN PYTHON

You can loop through the set items using for loop, or ask if a specified value is present in a set, by using the in keyword.

thisset = {"apple", "banana", "cherry"}
for x in thisset:
  print(x)

OUTPUT:

ACCESS SET IN PYTHON
OUTPUT – ACCESS SET IN PYTHON

2.2 CHECK IF ITEM EXISTS IN SET IN PYTHON

To check if ‘banana’ is present in the set:

thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)

OUTPUT:

CHECK ITEM IN SET IN PYTHON
OUTPUT – CHECK ITEM IN SET IN PYTHON

3. CHANGE ITEMS IN PYTHON

Once a set is created, you cannot change its items, but you can add new items.

4. ADD ITEMS IN SET IN PYTHON

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

4.1 add() METHOD OF SET IN PYTHON

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

thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)

OUTPUT:

ADD ITEM IN A SET IN PYTHON
OUTPUT – ADD ITEM IN A SET IN PYTHON

4.2 update() METHOD OF SET IN PYTHON

Add multiple items to the set using the update() method.

thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)

OUTPUT:

ADD MULTIPLE ITEM IN SET IN PYTHON USING UPDATE
OUTPUT – ADD MULTIPLE ITEM IN SET IN PYTHON USING UPDATE

5. GET THE LENGTH OF A SET IN PYTHON

To determine how many items a set has, use the len() method.

thisset = {"apple", "banana", "cherry"}
print(len(thisset))

OUTPUT:

LENGTH OF SET IN PYTHON
OUTPUT – LENGTH OF SET IN PYTHON

6. REMOVE ITEM FROM SET IN PYTHON

To remove an item in a set, use the remove(), or the discard() method.

thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)

thisset.discard("apple")
print(thisset)

OUTPUT:

using remove and discard remove item from set in python
OUTPUT – USING REMOVE AND DISCARD REMOVE ITEM FROM SET IN PYTHON

Leave a Reply

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