Practice
Resources
Contests
Online IDE
New
Free Mock
Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
Scaler
Explore Offerings by SCALER

Begin your success journey!

Sign Up using
Full name *
Email *
Password *

By creating an account, I acknowledge that I have read and agree to InterviewBit’s Terms and Privacy Policy .

Welcome back!

Log In using
Email *
Password *

Collections Module Tutorial

The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them.

Some of the built-in containers are Tuple, List, Dictionary, etc.
Some of the different containers provided by collections module are discussed below.

Counters

A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values.

from collections import Counter
my_list = [1, 1, 2, 3, 4, 5, 3, 2, 3, 4, 2, 1, 2, 3]
print Counter(my_list)
# prints Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})

print Counter(my_list).items()
# prints [(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]

print Counter(my_list).keys()
# prints [1, 2, 3, 4, 5]

print Counter(myList).values()
# prints [3, 4, 4, 2, 1]

DefaultDict

It’s similar to the usual dictionary (dict) container, but the only difference is that a defaultdict will have a default value if that key has not been set yet. If you didn’t use a defaultdict you’d have to check to see if that key exists, and if it doesn’t, set it to what you want.

from collections import defaultdict  
    
# Defining the dict
# When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.

d = defaultdict(int)  
     
my_list = [1, 2, 3, 2, 4, 2, 4, 1, 2]  
     
# Iterate through the list for keeping the count  

for i in my_list:     
    # The default value is 0 so there is no need to enter the key first  
    d[i] += 1

print(d)
# prints defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})

OrderedDict

An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged.

from collections import OrderedDict  

# Dictionary 
d = {}  
d['b'] = 1
d['a'] = 2
d['c'] = 3
d['d'] = 4
    
for key, value in d.items():  
    print(key, value)  
# This can be printed in any order    
# OrderDictionary 
od = OrderedDict()  
od['b'] = 1
od['a'] = 2
od['c'] = 3
od['d'] = 4
    
for key, value in od.items():  
    print(key, value)
# The order remains same as the key are inserted

ChainMap

A ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries.

from collections import ChainMap  

d1 = {'a': 1, 'b': 2} 
d2 = {'c': 3, 'd': 4} 
d3 = {'e': 5, 'f': 6} 
  
# Defining the chainmap  
c = ChainMap(d1, d2, d3)  

print(c)
# prints ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})

# Accessing Values using key name 
print(c['a']) 
# prints 1
  
# Accesing values using values() method 
print(c.values()) 
# prints ValuesView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}))
  
# Accessing keys using keys() method 
print(c.keys())
# prints KeysView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}))

NamedTuple

Basically, namedtuples are easy to create, lightweight object types.
They turn tuples into convenient containers for simple tasks.
With namedtuples, you don’t have to use integer indices for accessing members of a tuple.

from collections import namedtuple
Point = namedtuple('Point','x,y')
pt1 = Point(1,2)
pt2 = Point(3,4)
dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y )
print(dot_product)
# prints 11

Deque

Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations as compared to list with O(n) time complexity.

from collections import deque
d = deque()
d.append(1)
print(d)
# prints deque([1])

d.appendleft(2)
print(d)
# prints deque([2, 1])

d.clear() # empty the deque

d.extend('1')
print(d)
# prints deque(['1'])

d.extendleft('234')
print(d)
# prints deque(['4', '3', '2', '1'])
print(d.count('1'))
# prints 1

print(d.pop())
# prints '1'

print(d)
# prints deque(['4', '3', '2'])

print(d.popleft())
# prints '4'

print(d)
# prints deque(['3', '2'])

d.extend('7896')
print(d)
# prints deque(['3', '2', '7', '8', '9', '6'])

d.remove('2')
print(d)
# prints deque(['3', '7', '8', '9', '6'])

d.reverse()
print(d)
# prints deque(['6', '9', '8', '7', '3'])

d.rotate(3)
print(d)
# prints deque(['8', '7', '3', '6', '9'])

Try the following example in the editor below.

You are given two list of lowercase characters A of length N and B of length M. For each ith character in B print space separated indices of all the occurence of B[i] in A in a new line.

If the character is not present in A, then print -1.
Considered index to be 0-based.

Example Input

A = ['a', 'a', 'b', 'a', 'b', 'c', 'x']
B = ['a', 'x', 'z']

Example Output

0 1 3 
6 
-1 
Start solving Collections Module Tutorial on Interview Code Editor
Hints
  • Complete Solution

Discussion


Loading...
Click here to start solving coding interview questions
Free Mock Assessment
Fill up the details for personalised experience.
All fields are mandatory
Current Employer *
Enter company name *
Graduation Year *
Select an option *
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Graduation Year *
Graduation Year *
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
*Enter the expected year of graduation if you're student
Current Employer *
Company Name *
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test