December 2018
Beginner to intermediate
796 pages
19h 54m
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