Comprehension & Generator Expression

Last Updated :
Discuss
Comments

Question 1

Which syntax correctly represents a list comprehension?

  • {x for x in range(5)}

  • [x for x in range(5)]

  • (x for x in range(5))

  • x in [range(5)]

Question 2

What is the output of this list comprehension?

Python
res = [x**2 for x in range(1, 4)]
print(res)


  • [1, 2, 3]

  • [1, 4, 9]

  • (1, 4, 9)

  • {1, 4, 9}

Question 3

Which comprehension will create a dictionary of numbers and their cubes (1 to 3)?

  • {x: x*x for x in range(1, 4)}

  • {x: x**3 for x in range(1, 4)}

  • {x*x: x for x in range(1, 4)}

  • dict(x: x**3 for x in range(1, 4))

Question 4

What will the following code return?

Python
a = [1, 2, 2, 3, 4]
res = {x for x in a if x % 2 == 0}
print(res)



  • [2, 4]

  • {2, 2, 4}

  • {2, 4}

  • (2, 4)

Question 5

What is the output of this list comprehension?

Python
res = [x for x in range(5) if x % 2 == 0]
print(res)


  • [1, 3, 5]

  • [0, 2, 4]

  • [0, 1, 2, 3, 4]

  • [2, 4]

Question 6

Which comprehension creates a dictionary from two lists using zip()?

Python
states = ["Texas", "California"]
capitals = ["Austin", "Sacramento"]


  • {s: c for c, s in zip(states, capitals)}

  • {state: capital for state, capital in zip(states, capitals)}

  • {state for state in states}

  • dict(zip(states, capitals))

Question 7

Which of these best describes a set comprehension?

  • Creates a sorted list

  • Creates a tuple

  • Creates a collection of unique elements

  • Creates a dictionary

Question 8

What is the output of this set comprehension?

Python
res = {x**2 for x in [1, 2, 2, 3]}
print(res)


  • [1, 4, 9]

  • {1, 4, 9}

  • (1, 4, 9)

  • {1:1, 2:4, 3:9}

Question 9

Which statement about dictionary comprehensions is TRUE?

  • Keys must be strings

  • Values must be lists

  • Comprehension must have ‘if’ condition

  • Key-value pairs are generated dynamically

Question 10

What does this expression return?

Python
[x*2 for x in range(4) if x != 2]


  • [0, 2, 6]

  • [0, 2, 4, 6]

  • [0, 2, 6]

  • [0, 2, 6]

There are 12 questions to complete.

Take a part in the ongoing discussion