set comprehensions
Just as you can create a set
using curly brackets ({}
), you can also create a set using set
comprehensions. These work in a way similar to list
comprehensions, but the values are unique (and without sort order):
>>> [x*y for x in range(3) for y in range(3)] [0, 0, 0, 0, 1, 2, 0, 2, 4] >>> {x*y for x in range(3) for y in range(3)} {0, 1, 2, 4}
Note
As is the case with the regular set, set
comprehensions support only hashable types.
Get Mastering Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.