Python Sets :

Creating Values in Sets :

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

Example :

  1. onset = {"ayan", "dev", "apu", "symul"}
  2. print(onset) #print full set
  3. input()

Output :

python sets creating

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

Access Values (Items) in Sets :

You cannot access items in a set by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

Example :

  1. onset = {"ayan", "dev", "apu", "symul"}
  2. for x in onset: print(x) #Loop through the set, and print the values
  3. if "apu" in onset:
  4. print("\n Yes, 'apu' is in the set") #Check if "apu" is present in the tuple
  5. input()

Output :

python set value/items accessing

Sets with methods :

python list have built-in methods, methods help us to manipulate sets items.

Example :

  1. onset = {"ayan", "dev", "apu", "symul"}
  2. onset.add("alex") #Add an item to a set
  3. print(onset)
  4. onset.update(["rayan", "jonas", "tomas"]) #Add multiple items to a set
  5. print(onset)
  6. print(len(onset)) #Get the number of items in a set
  7. onset.remove("alex") #Remove "alex" item using the "remove()" method
  8. print(onset)
  9. onset.remove("rayan") #Remove "rayan" item using the "discard()" method
  10. print(onset)
  11. input()

Output :

python sets with methods

Sets methods :

Python includes many built-in methods but here we just adding some of the following built-in methods to manipulate sets :

  • The add() method to add one item to a set.
  • The update() method to add multiple items to a set.
  • The len() method to determine how many items a set has.
  • The remove() method to remove an item in a set.
  • The discard() method also use for remove an item in a set.
  • The copy() method to returns a copy of the set.
  • The clear() method to removes all the elements from the set.

Next Update


Currently we improved our website User Interface and other contents. Our next update is adding video tutorials on this site so, We create a new YouTube channel, our YouTube channel name is CodeX.

We need some time for make video tutorials (CodeX) so, stay with us and keep supporting and you know already we make a Collaboration with HackIsOn YouTube channel long time ago So, please Subscribe Our Channels