SET DATA-TYPE


SET DATA-TYPE

Set is an unordered collection of data types. It is iterable and mutable(can be modified after creation). In set, the order of the elements is undefined, and it may return the changed sequence. set() is the built-in function for creating the set.

Creating Sets in Python:

We can create sets in python by using the in-built set() function with an iterable object. We can also use a sequence by putting the sequence inside curly braces, which can be parted using a "comma." It is not necessary to use the same type of elements in a set, and several mixed-up datatype elements are allowed in the set.

Accessing elements of Sets in python:

The sets in python are unordered, and the items contain no index. So, you are allowed to loop through the set items by using a for a loop. And inquire if any specified value is available in a set using the keyword.

Adding some items in the set:

In this, python gives you the add() method and update() method so that you can add any appropriate item to the set accordingly. The add() method allows you to add only one element, whereas the update() method allows you to add several elements in a set.

Remove and discard any items from the set:

Python gives you the discard() and removes () method to remove any items from the set. Both the functions perform the same task, but the main difference between discard() and remove() is that:-

  • If you remove something using the discard() function, and it doesn't even exist in the set, then the set will remain unchanged and will not raise any error.
  • If you remove something using the remove() function, and it doesn't even exist in the set, it will give an error.

Example No.1:

web = {"Knowledge2life 1", "Knowledge2life 2", "Knowledge2life 3"} print(web)

OUTPUT:

{'Knowledge2life 3', 'Knowledge2life 1', 'Knowledge2life 2'}

Example No.2:

web = {"knowledge2life 1", "knowledge2life 1", "knowledge2life 2"} print(web)

OUTPUT:

{'Knowledge2life 1', 'Knowledge2life 2'}