Sets in Python

Set is an unordered collection of unique items. It is used to store multiple items without any duplicates. Set is defined by values separated by commas inside braces { }. They are mutable, which means their values can be modified.

For example,

  • # create a set named student_id

student_id = {112, 114, 116, 118, 115}

# display student_id elements

print(student_id)

# display type of student_id

print(type(student_id))

Output:

{112, 114, 115, 116, 118}

<class ‘set’>

Here, we have created a set named student_info with 5 integer values.

Since sets are unordered collections, indexing has no meaning. Hence, the slicing operator [ ] does not work.

  • my_set = {1, 8, “Karachi”, “P”, 0, 8}

print(my_set)

print(“Its data type:”, type(my_set))

Result:

{0, 1, ‘P’, 8, ‘Karachi’}

Its data type: <class ‘set’>

Access Set Items:

Set items cannot be accessed by referring to an index; since sets are unordered, the items have 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 the keyword. 

We can transform set() function using some built-in functions. 

Like: add(), update(), remove(), clear(), copy(), update(), union() etc.

  • # Set operations

set1 = {1, 2, 3, 4, 5}

set2 = {4, 5, 6, 7, 8}

# Union of sets

union = set1.union(set2)

# Intersection of sets

intersection = set1.intersection(set2)

# Difference of sets

difference = set1.difference(set2)

# Printing the results

print(union)

print(intersection)

print(difference)

Output:

{1, 2, 3, 4, 5, 6, 7, 8}

{4, 5}

{1, 2, 3}

Advantages of Sets:

  • Unique Elements
  • Fast Membership Testing
  • Mathematical Set Operations
  • Mutable

Disadvantages of Sets:

  • Unordered
  • Limited Functionality
  • Memory Usage
  • Less Commonly Used
Visited 18 times, 1 visit(s) today