lettura simple

Set Comprehension in Python

Welcome to today's lesson, where we'll dive deep into the concept of set comprehension in the Python language.

You might wonder, what is set comprehension? In the simplest terms, it's a convenient syntax that allows us to construct a set with numerous elements, each of which adheres to a particular selection criterion.

To help you grasp this better, let's explore a hands-on example.

Imagine you're tasked with creating a set comprising the first 1000 even numbers. Technically, you could jot them all down manually, but that would be both time-consuming and error-prone.

Here's where set comprehension comes into play, allowing you to generate the same set with just a single line of code:

>>> P={i for i in range(1000) if i%2==0}

What you're left with is an elegantly constructed set of even numbers, ranging from 0 to 1000.

  • The 'for' loop iterates over numbers from 0 to 1000, cherry-picking only those which, when divided by two, leave a remainder of zero (if i%2==0)
  • The numbers meeting this condition are subsequently added to the variable 'P'.

The variable 'P' is deemed a 'set' type as its elements are ensconced within a pair of curly braces.

Thus, you have your first 1000 even numbers.

first 1000 even numbers

Now, you may ask, why choose set comprehension?

The beauty of set comprehension lies in its brevity and speed when compared to a conventional iteration.

For instance, you could indeed create a set of even numbers up to 1000 using a loop:

  1. P=set()
  2. for i in range(1000):
  3. if (i%2==0):
  4. P.add(i)

Yet in doing so, you've used four lines of code.

Furthermore, creating the set via looping would take approximately double the time compared to the swift and efficient set comprehension.

In conclusion, set comprehension in Python not only allows for more concise code but also provides a faster method for generating sets, proving to be a valuable tool for any Pythonista.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin