Article by: Manish Methani
Last Updated: October 5, 2021 at 8:04am IST
In Python, a set is a collection of unique elements that are unordered and unindexed. This means that you cannot access the elements of a set using an index or a key, but you can iterate through the elements using a loop. In this tutorial, we will cover the basics of Python sets, set comprehension, and looping through sets.
A set in Python is created using curly braces {} or the set() function. Let's create a set of fruits as an example:
fruits = {"apple", "banana", "cherry"}
We can also use the set() function to create a set:
fruits = set(("apple", "banana", "cherry"))
Notice that we use a double set of parentheses when creating a set using the set() function.
Set comprehension is a concise way to create a set based on some condition or expression. The syntax for set comprehension is similar to list comprehension, but we use curly braces {} instead of square brackets []. Let's create a set of even numbers from 1 to 10 using set comprehension:
even_numbers = {x for x in range(1, 11) if x % 2 == 0} print(even_numbers) # Output: {2, 4, 6, 8, 10}
In the above example, we use set comprehension to create a set of even numbers from 1 to 10. We iterate through the range of numbers from 1 to 10, and we only add the number to the set if it is even (x % 2 == 0).
To loop through a set, we can use a for loop. Since sets are unordered, we cannot rely on the order of the elements. Let's loop through the fruits set that we created earlier:
fruits = {"apple", "banana", "cherry"} for fruit in fruits: print(fruit)
Output:
apple banana cherry
In the above example, we use a for loop to loop through the fruits set. Since sets are unordered, the order of the elements in the output may vary.
In this tutorial, we covered the basics of Python sets, set comprehension, and looping through sets. Sets are a useful data structure in Python, especially when we need to store unique elements. Set comprehension is a concise way to create sets based on conditions or expressions. Looping through sets can be done using a for loop, but we cannot rely on the order of the elements since sets are unordered.