Iterate over a set in Python
Set is a collection of unique objects, which means there are no duplicate elements. And loop through the set to extract the objects each at a time, consider the following to know more.
for loop in set Python
The 'for' loop in Python is different form the 'for' loop in the other programming languages.
In Python, the 'for' loop does not require any update to be done. It automatically update after each iteration.
Python 'for' loop syntax
Example
Input
2
3
4
5
'for' loop over set with range() method
Loop over a set, like above can be done with the range() method.
We can not access the set using index because, they are unordered.
So we have to make use of iter() built-in method to convert the set into interable whose elements can be accessed by specifying index.
Program
Input
Output
2
3
4
5
Program
Input
Output
4
5
Program
Input
b = {1, 2, 3, 4, 5, 6, 7, 8, 9}Output
'for' loop over set with enumerate() method
The enumerate() method enumerates the set, with numbers.
Following is an example to enumerate the set.
Program
Input
b = {1, 2, 3, 4, 5, 6, 7, 8, 9}Output
Here is an example, how you can fetch the content, got after enumerating the set. Both, set value and the enumerated value.
Program
Input
for i, j in list(enumerate(b)):
print("Index: ", i, " Value: ", j)
Output
Set comprehension
Set comprehension with 'for' loop gives a lot of information with 1 line of sentence and is more easy and readable.
Creating a set using set comprehension with 'for' loop
Following is the program which will create a set without using set comprehension.
Program
Input
Output
Now this is how you can create a set using set comprehension with just one line of code. Which is so easy.
Program
Input
compre = {value for value in range(0, 10)}Output
Set comprehension with an expression
Let's put an expression at the beginning of for loop.
Here is an example, which will raise each value with the power of 2.
Program
Input
Output
Set/ tuple collection with set comprehension
Creation of set which will be the collection of set / tuple, using set comprehension.
The following code will have the collection of tuples, in which the two elements of each tuple will not be equal to each other.
Program
Input
Output
Set comprehension with a function
Introducing a function at the beginning of the set comprehension, is also possible.
Set comprehension with built-in function
Program
Input
a = {1, 2, 3}
Output
Set comprehension using the user defined function
First of all we define a function, and then introduce it into the set comprehension.
Program
Input
Output
{3, 4, 5, 6, 7}
Post a Comment
If you have any query, feel free to ask.