Python Logo

Set


What are Python sets?

Python sets are unordered collections of unique elements. This means that the elements in a set are not in any particular order, and each element can only appear in the set once. Sets are created using curly braces ({}) and can contain any type of data, including integers, floats, strings, lists, and dictionaries.

How to create a Python set

To create a Python set, you simply enclose the elements of the set in curly braces. For example:

 

Python

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

This code creates a set containing the numbers 1 through 5.

How to access items in a Python set

Since sets are unordered, there is no way to access specific items in a set by index. However, you can use the in operator to check if an item is contained in a set. For example:

 

Python

print(1 in my_set)  # Outputs True
print(6 in my_set)  # Outputs False
 

You can also use the &, |, and - operators to perform set operations on two sets, such as union, intersection, and difference. For example:

 

Python

my_set2 = {6, 7, 8, 9, 10}

# Union of two sets
my_set_union = my_set | my_set2

# Intersection of two sets
my_set_intersection = my_set & my_set2

# Difference of two sets
my_set_difference = my_set - my_set2
 

How to iterate over a Python set

To iterate over a Python set, you can use the for loop. The for loop iterates over each item in the set and executes a block of code for each item. For example:

 

Python

for item in my_set:
  print(item)
 

This code will print each item in the set to the console in an arbitrary order.

Python set methods

There are a few Python set methods that can be used to perform various tasks on sets, such as adding and removing items from a set, checking if a set is empty, and finding the union, intersection, and difference of two sets.

Here are some examples of Python set methods:

  • add(item): Adds the specified item to the set.
  • remove(item): Removes the specified item from the set.
  • clear(): Removes all items from the set.
  • isdisjoint(other_set): Returns True if the set is disjoint from the other set, False otherwise.
  • union(other_set): Returns a new set containing the union of the two sets.
  • intersection(other_set): Returns a new set containing the intersection of the two sets.
  • difference(other_set): Returns a new set containing the difference of the two sets.

Here are some additional tips for using Python sets:

  • Use descriptive variable names for your sets. This will make your code more readable and easier to maintain.
  • Add comments to your code to explain what your sets are used for. This will help other developers understand your code and make it easier to debug.
  • Sets are a good choice for storing data that needs to be unique and unordered.
  • Use the isinstance() function to check the data type of a variable before using it as a set. This can help you to avoid errors.