Double Loop
We create a set with curly braces, just like we do for a dictionary.
But sets don’t have a colon to separate keys and values.
Sets
{round(x/y) for y in range(1, 11) for x in range(2, 21)}
Output
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
Compare with list comprehension
{round(x/y) for y in range(1, 11) for x in range(2, 21)}
Output
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 2, 2, 3, 4, 4, 4, 5, 6, 6, 6, 7, 8, 8, 8, 9, 10, 10, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]
Fizz Buzz (Omitting Repetition with Set Comprehension)
total_nums = range(1, 101)
fizzbuzzes = {
'fizz': [n for n in total_nums if n % 3 == 0],
'buzz': [n for n in total_nums if n % 7 == 0]
}
fizzbuzzes = {key: set(value) for key, value in fizzbuzzes.items()}
Output
>>> fizzbuzzes
{'fizz': {3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99}, 'buzz': {98, 35, 70, 7, 42, 77, 14, 49, 84, 21, 56, 91, 28, 63}}
fizzbuzzes['fizzbuzz'] = {n for n in fizzbuzzes['fizz'].intersection(fizzbuzzes['buzz'])}
Output
>>> fizzbuzzes['fizzbuzz']
{42, 84, 21, 63}