top of page
Writer's pictureCodersarts AI

What Is A Set In Python? How to use set in python?

It is a collection type which can store elements of different data types but doesn’t index them in a particular order. It look likes mathematics set.




Properties Of A Set:


A Python Set has the following properties:


  • The elements don’t have a specific order, hence, shall exist in a random style.

  • Each item is unique in a Set and therefore, can’t have duplicates.

  • The elements are immutable and hence, can’t accept changes once added.

  • A set is itself mutable and allows addition or deletion of items.

Also, remember, the elements can be of any types such as an integer, a float, a tuple, or strings, etc. The only exception with a Set is that it can’t store a mutable item such as a list, a set or a dictionary.


Example:

Create s set of numbers

py_set_num = {3,7,11,15}

print(py_set_num )


Executing the above code will return the following output.

Use with multiple format data.


Example:

py_set_num = {3, 7, (1,2), "11", 1.1}

print(py_set_num )


How To Modify A Set In Python?


In this add() which adds a single element and the update() which can add more than one item.

The update() method can even accept tuples, lists, strings or other sets as an argument. However, duplicate elements will automatically get excluded.


Example: add()

py_set_num = {3,7,11,15}

py_set_num.add(99)

print("The value of new set is" , py_set_num )


Example:Update()

py_set_num = {3,7,11,15}

py_set_num.update(10,15,20)

print("The value of new set is" , py_set_num )


If you like Codersarts blog and looking for Programming Assignment Help Service,Database Development Service,Web development service,Mobile App Development, Project help, Hire Software Developer,Programming tutors help and suggestion  you can send mail at contact@codersarts.com.



7 views0 comments

Comments


bottom of page