June 2018
Beginner
508 pages
13h 8m
English
The set comprehensions are very similar to list and dictionary ones. Python allows both the set() constructor to be used, or the explicit {} syntax. Let's see one quick example:
# set.comprehensions.pyword = 'Hello'letters1 = set(c for c in word)letters2 = {c for c in word}print(letters1) # prints: {'H', 'o', 'e', 'l'}print(letters1 == letters2) # prints: True
Notice how for set comprehensions, as for dictionaries, duplication is not allowed and therefore the resulting set has only four letters. Also, notice that the expressions assigned to letters1 and letters2 produce equivalent sets.
The syntax used to create letters2 is very similar to the one we can use to create a dictionary comprehension. You can spot the difference ...
Read now
Unlock full access