Python Collection Module

Last Updated :
Discuss
Comments

Question 1

Which of the following is not a part of the collections module in Python?

  • A

    Counter

  • B

    OrderedDict

  • C

    ArrayList

  • D

    deque

Question 2

What is the output of the following code?


from collections import

Counterprint(Counter('gfg'))

  • A

    Counter({'g': 1, 'f': 1})

  • B

    Counter({'g': 2, 'f': 1})

  • C

    Counter({'f': 2, 'g': 1})

  • D

    {'g': 2, 'f': 1}

Question 3

What is the output of this code?

Python
from collections import defaultdict
d = defaultdict(lambda: 'Not Present')
d['a'] = 10
print(d['a'], d['b'])



  • A

    10 KeyError

  • B

    10 Not Present

  • C

    10 None

  • D

    KeyError Not Present

Question 4

Which collections class maintains the order in which keys are inserted?

  • A

    OrderedDict

  • B

    defaultdict

  • C

    Counter

  • D

    deque

Question 5

What will be the final order of keys in this code?

Python
from collections import OrderedDict

od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3

od.move_to_end('b')

print(list(od.keys()))
  • A

    ['a', 'c', 'b']

  • B

    ['b', 'a', 'c']

  • C

    ['a', 'b', 'c']

  • D

    ['c', 'b', 'a']

Question 6

Given this code, what will be the output?

Python
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(1, y=3)
print(p.x + p.y)
  • A

    4

  • B

    3

  • C

    TypeError

  • D

    SyntaxError

Question 7

Which collection type is best for implementing a stack or queue efficiently?

  • A

    list

  • B

    deque

  • C

    set

  • D

    tuple

Question 8

What will be the result of this code?

Python
from collections import Counter
c = Counter(a=2, b=3)
d = Counter(a=1, b=2)
print(c - d)
  • A

    Counter({'a': 1, 'b': 1, 'c': 0})

  • B

    Counter({'a': -1, 'b': -1})

  • C

    Counter()

  • D

    Counter({'a': 1, 'b': 1})


Question 9

Which of the following features is unique to ChainMap?

  • A

    It chains multiple dictionaries into a single view

  • B

    It maintains the insertion order of keys

  • C

    It counts frequency of elements

  • D

    It provides default values for missing keys

Question 10

What will the following code print?

Python
from collections import ChainMap

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
cm = ChainMap(dict1, dict2)
print(cm['b'])
  • A

    4

  • B

    3

  • C

    2

  • D

    KeyError

There are 10 questions to complete.

Take a part in the ongoing discussion