From the course: Python Data Structures: Sets and Frozen Sets
Set comprehension - Python Tutorial
From the course: Python Data Structures: Sets and Frozen Sets
Set comprehension
- [Instructor] Create a set of all even numbers from one to 10. Let us create a even numbers set. At the moment we have empty set and now we can iterate over all numbers from one to 10. For number in range, one to 11. Inside of range, we are using one to 11 instead of one to 10 because we want to include 10 in our result Range method excludes the end value. That is why we have taken 11 here. Now, if number modulus 2 == 0, then we want that number to be present inside our even numbers set. Even numbers.add number Add number add is a built in method. We'll be discussing about add method in the following lessons present in this course. Add is helping us in adding numbers to our empty set. And here we can print the result. Even numbers present in the set are, let us just print even numbers. Python 3, comprehension.py. Even numbers present in the set are 2, 4, 6, 8, 10. Now, how we can solve the same problem using comprehension? Let us see. Set comprehension is a way of creating a new set based on existing set. Comprehensions are more concise in comparison to the normal for loop. Even numbers is our new set. Here we can write curly brackets and inside of our curly brackets, we can use for loop. So for number in range one to 11, if number modulus 2 == 0, then we want those numbers to be present inside our new set. First the expression gets executed, then it checks whether the number is even or not. If the number is even, then we are adding that number to the set. All of this with a single line of code. And here we can print a result. Even numbers present in the set are even numbers. Also, just to differentiate it, we can write print statement followed by double equal two. And here I'm writing an explanatory statement that says solution using set comprehension. Let us just run our program. So you can see, our solution using set comprehension is even numbers present in the set are 2, 4, 6, 8, 10. Using comprehension is considered as a more elegant way to solve the problem. However, don't use comprehension when you have too much of conditional statements present inside your loop. Otherwise, it would reduce the readability of your program.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.