Comprehension & Generator Expression

Last Updated :
Discuss
Comments

Question 1

Which syntax correctly represents a list comprehension?

  • A

    {x for x in range(5)}

  • B

    [x for x in range(5)]

  • C

    (x for x in range(5))

  • D

    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)


  • A

    [1, 2, 3]

  • B

    [1, 4, 9]

  • C

    (1, 4, 9)

  • D

    {1, 4, 9}

Question 3

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

  • A

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

  • B

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

  • C

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

  • D

    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)



  • A

    [2, 4]

  • B

    {2, 2, 4}

  • C

    {2, 4}

  • D

    (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)


  • A

    [1, 3, 5]

  • B

    [0, 2, 4]

  • C

    [0, 1, 2, 3, 4]

  • D

    [2, 4]

Question 6

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

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


  • A

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

  • B

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

  • C

    {state for state in states}

  • D

    dict(zip(states, capitals))

Question 7

Which of these best describes a set comprehension?

  • A

    Creates a sorted list

  • B

    Creates a tuple

  • C

    Creates a collection of unique elements

  • D

    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)


  • A

    [1, 4, 9]

  • B

    {1, 4, 9}

  • C

    (1, 4, 9)

  • D

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

Question 9

Which statement about dictionary comprehensions is TRUE?

  • A

    Keys must be strings

  • B

    Values must be lists

  • C

    Comprehension must have ‘if’ condition

  • D

    Key-value pairs are generated dynamically

Question 10

What does this expression return?

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

    [0, 2, 6, 8]

  • B

    [0, 2, 4, 6]

  • C

    [2, 6, 8]

  • D

    [0, 2, 6]

There are 12 questions to complete.

Take a part in the ongoing discussion