search

What is a set in Python and how to use it?

A set in Python is an unordered collection of unique elements, where duplicates are not allowed. A set is defined using curly braces or the built-in "set()" function. For example:

# Using curly braces
fruits = {'apple', 'banana', 'cherry'}

# Using the set function
fruits = set(['apple', 'banana', 'cherry'])

A set is similar to a dictionary, but instead of key-value pairs, it only contains elements. You can use a set to perform various set operations such as union, intersection, difference, and others.

Here are some common use cases for sets:

Removing duplicates from a list: You can convert a list to a set to remove duplicates and then convert it back to a list if you need the elements to be ordered.

Fast membership testing: Since sets are implemented as hash maps, checking if an element exists in a set is very fast, and takes constant time on average.

Set operations: As mentioned before, sets provide various set operations that you can use to manipulate the elements in the set.

Here are some common set operations in Python:

union (|) : Returns a set that contains all elements from both sets.

intersection (&): Returns a set that contains only elements that are present in both sets.

difference (-): Returns a set that contains elements that are present in the first set but not in the second set.

symmetric_difference (^): Returns a set that contains elements that are present in one set but not in the other.

issubset (<=): Returns True if the set is a subset of the other set, meaning that all elements in the first set are present in the second set.

issuperset (>=): Returns True if the set is a superset of the other set, meaning that all elements in the second set are present in the first set.

Related Questions You Might Be Interested