Comprehensions & Generators · Question 9 · Medium

A comprehension has two for clauses, one over range(2) and one over a string. In what order are the pairs produced?

print([(a, b) for a in range(2) for b in "xy"])
  1. [(0, 'x'), (1, 'x'), (0, 'y'), (1, 'y')]
  2. [(0, 'x'), (1, 'y')]
  3. [(0, 1), ('x', 'y')]
  4. [(0, 'x'), (0, 'y'), (1, 'x'), (1, 'y')]
Answer and explanation

Answer: D. [(0, 'x'), (0, 'y'), (1, 'x'), (1, 'y')]

Explanation: The for clauses nest left to right, so the first is the outer loop. For a = 0 the inner loop gives x then y, and the same repeats for a = 1.

Previous: A conditional expression is used in the output part of a comprehension to mark… · Next: The same generator expression is passed to sum twice. What do the two calls…

Practise comprehensions & generators

Try a fresh set of comprehensions & generators questions with an explanation after every answer, free and without signing up: Comprehensions & Generators practice. Or sit a full placement mock test.

More comprehensions & generators questions

More python practice

Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge