Learn Python
Lesson 1 - Introduction To Python
Lesson 2 - Basic Python Syntax
Lesson 3 - Control Flow
Lesson 4 - Functions
Lesson 6 - Exception Handling
Lesson 7 - Modules And Packages
Lesson 8 - Basic String Operations
Lesson 9 - Object-Oriented Programming (OOP)
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.