Comprehensions & Generators · Question 8 · Medium

A conditional expression is used in the output part of a comprehension to mark pass (P) or fail (F). What is printed?

print(["P" if m >= 40 else "F" for m in [55, 32, 40]])
  1. ['P', 'P']
  2. ['P', 'F', 'P']
  3. ['P', 'F', 'F']
  4. SyntaxError
Answer and explanation

Answer: B. ['P', 'F', 'P']

Explanation: An if-else before the for chooses a value for every item, so the list keeps all three positions. 55 and 40 are at least 40 (P) and 32 is not (F).

Previous: What does calling next(g) do when g is a generator that still has values left? · Next: A comprehension has two for clauses, one over range(2) and one over a string…

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