Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 5 - Basic Data Structures

5.4 Sets

Sets in Python are unordered collections of unique elements, enclosed by {}. Sets do not support duplicate values, distinguishing them from lists, tuples, and dictionaries.

Sets are often used for mathematical operations and handling unique collections of items.

Unlike lists, tuples, and dictionaries, accessing elements directly from a set isn't straightforward due to their unordered nature. Here are three common methods to work with sets:

1. Iteration: You can iterate over a set using a loop to access each value individually:

my_set = {1, 2, 3, 4, 5}
for value in my_set:
    print(value)

This will print each value in my_set on a new line.

2. Check existence: To check if a specific value exists in a set, use the in operator:

my_set = {1, 2, 3, 4, 5}
if 2 in my_set:
    print("Value 2 exists")

Try running this code snippet to verify if the value 2 exists in the set my_set.

3. Converting to List: If you need to access set values by index or position, you can convert the set to a list and then access elements as you would in a list:

my_set = {1, 2, 3, 4, 5}
my_list = list(my_set)
print(my_list[1])

In this example, my_set is converted to my_list, allowing you to access elements by index. Remember, however, that the order of elements in a set is not guaranteed, so the order in my_list may differ from the original set.