Python Sets

Sets in Python are unordered collections of unique elements. Sets are useful for tasks that require membership testing and eliminating duplicate entries. In this lesson, we will cover the basics of sets and how to work with them.

Creating Sets

You can create a set in Python by enclosing comma-separated values in curly braces {}. For example:

fruits = {'apple', 'banana', 'cherry'}
numbers = {1, 2, 3, 4, 5}
empty_set = set()

Accessing Elements

Since sets are unordered, you cannot access elements by index. Instead, you can check for membership using the in keyword. For example:

print('apple' in fruits)  # Output: True

Adding and Removing Elements

You can add elements to a set using the add() method and remove elements using theremove() method. For example:

fruits.add('orange')
print(fruits)  # Output: {'apple', 'banana', 'cherry', 'orange'}

fruits.remove('banana')
print(fruits)  # Output: {'apple', 'cherry', 'orange'}

Set Operations

Sets support various mathematical operations such as union, intersection, difference, and symmetric difference. These operations can be performed using methods or operators. For example:

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

union_set = set1 | set2
intersection_set = set1 & set2
difference_set = set1 - set2
symmetric_difference_set = set1 ^ set2

Conclusion

Sets are a useful data structure in Python for storing unique elements and performing set operations. By understanding how to create and work with sets, you can efficiently manage collections of data in your Python programs.



[ Footer Placeholder]