Set comprehensions

Sets support a similar comprehension syntax using, as you might expect, curly braces. Our previous "number of digits in factorials" result contained duplicates, but by building a set instead of a list we can eliminate them:

>>> s = {len(str(factorial(x))) for x in range(20)}
>>> s
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 18}

Like list comprehensions, set comprehension produce standard set objects:

>>> type(s)
<class 'set'>

Note that, since sets are unordered containers, the resulting set is not necessarily stored in a meaningful order.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset