Site icon Care All Solutions

Sets

Sets in Python

Sets are unordered collections of unique elements. They are mutable and do not allow duplicates.

Creating Sets

Python

# Empty set
empty_set = set()

# Set with elements
numbers = {1, 2, 3, 2, 4}  # Duplicates are removed

Accessing Set Elements

Unlike lists and tuples, sets do not support indexing. You cannot access elements by their position. However, you can check if an element is present in a set using the in keyword.

Python

my_set = {1, 2, 3}
print(2 in my_set)  # Output: True

Set Operations

Sets support mathematical set operations:

Key Points

How do you create an empty set?

Use set() to create an empty set.

Are sets mutable?

Yes, sets are mutable

Can sets contain duplicate elements?

No, sets only contain unique elements.

Are sets ordered?

Sets are unordered, meaning the elements don’t have a specific position.

How do you add an element to a set?

Use the add() method.

How do you remove an element from a set?

Use the remove() or discard() methods.

What is the difference between remove() and discard()?

remove() raises a KeyError if the element is not found, while discard() does nothing.

Can I use sets for mathematical set operations?

Yes, sets support operations like union, intersection, difference, and symmetric difference.

Can I use a set as a dictionary key?

Yes, as long as the elements in the set are hashable.

Read More..

Exit mobile version