results = []for m inrange(2):for n inrange(3): results.append((m,n))results
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
results = [(m,n) for m inrange(2) for n inrange(3)]results
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
Tip
Nested comprehension are difficult to read and debug. As a rule of thumb, do not use comprehensions for nested logic beyond 2 levels and, in general, do not add too much logic to comprehensions. If in doubt, just write the loop(s) out.
Although lists are the most commonly used, comprehensions also extend to other collections beyond lists.
8.2 Tuple comprehensions
tuple(n for n inrange(10))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
8.3 Set comprehensions
results =set()for n inrange(10):if n >2: results.add(n)results
{3, 4, 5, 6, 7, 8, 9}
results = {n for n inrange(10) if n >2}results
{3, 4, 5, 6, 7, 8, 9}
8.4 Dictionary comprehensions
results = {}for n inrange(10):if n >2: results[f"number_{n}_is"] = nresults