The Python collections contains different type of containers. The container is an object which holds different elements and can access the elements and iterate over the object. It contains containers like list, dict, set etc to improve the functionalities of the this containers collections module was introduced.
The collection module provides alternative to the built in data types such as list, tuples, dictionary and sets. It provides additional data structures and operations that are more efficient than the built-in types in certain situations.
Here, in the following table we can find different containers with there functionality −
container functionality factory function for creating tuple subclasses with named fields list-like container with fast appends and pops on either end dict-like class for creating a single view of multiple mappings dict subclass for counting hashable objects dict subclass that remembers the order entries were added dict subclass that calls a factory function to supply missing values wrapper around dictionary objects for easier dict subclassing wrapper around list objects for easier list subclassing wrapper around string objects for easier string subclassing namedtupleThe namedtuple() in Python is a data type from the collections module. It assigns a name to each position in a tuple, allowing elements to be accessed by field names, similar to how we access elements in a tuple by index.
SyntaxFollowing is the syntax of the Python namedtuple() data type −
class collections.namedtuple(typename, field_names, rename, default)Example
Following is the basic example of the Python namedtuple() data type −
from collections import namedtuple student1 = namedtuple('student1',['name','rollno', 'marks']) var = student1(name = 'Sai',rollno=237, marks=89) print("Name :",var.name) print("Rollno :",var.rollno) print("Marks :",var.marks)
Following is the output of the above code −
Name : Sai Rollno : 237 Marks : 89deque
In Python, deque() is one of the datatypes, which returns a new deque object initialized left-to-right (using append()) with data from iterable. If iterable is not specified, the new deque is empty.
The deque is implemented using collections module. When we need to perform faster operations like append and pop an element we prefer deque as its time complexity is O(1) time as compard to list that provides O(n) time complexity.
SyntaxFollowing is the syntax of the Python deque() class −
class collections.deque([iterable[, maxlen]])Example
Following is an basic example of Python deque() class −
from collections import deque d = deque('xyz') print(d)
Following is the output of the above code −
deque(['x', 'y', 'z'])ChainMap
In Python, ChainMap class is used to convert multiple dictionaries or mappings into single unit. If no maps are specified, a single empty dictionary is provided so that a new chain always has at least one mapping.
The ChainMap() class is defined in Collections module. It is often much faster than creating a new dictionary.
SyntaxFollowing is the syntax of the Python ChainMap() −
collections.ChainMap(iterable1, iterable2, iterable3)Example
Following is an basic example of the Python ChainMap() −
# Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'one': 1, 'two': 2} d2 = {'three': 3, 'four': 4} d3 = {'five': 5, 'six': 6} # Defining the chainmap c = ChainMap(d1, d2, d3) print(c)
Following is the output of the above code −
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4}, {'five': 5, 'six': 6})Counter
Python Counter is a container that hold count of objects. It is used to count items available or exist in iterables. Counts are allowed to be any integer value including zero or negative counts.
Counter is a subclass of the dictionary. It represents data as a key and value. It inherites all the methods and properties of the dictionary. It allows to perform artimetic and set operations. It can be used with any iterable which implements iteration protocol.
SyntaxFollowing is the syntax of the Python Counter−
class collections.Counter([iterable-or-mapping])Example
In the following example we have initializated the Counter in different ways −
from collections import Counter # With sequence of items print(Counter(['x','x','z','x','y','z','x','x','z','x'])) # with dictionary print(Counter({'y':3, 'z':5, 'x':2})) # with keyword arguments print(Counter(z=3, x=5, y=2))
Following is the output of the above code −
Counter({'x': 6, 'z': 3, 'y': 1}) Counter({'z': 5, 'y': 3, 'x': 2}) Counter({'x': 5, 'z': 3, 'y': 2})OrderDict
In Python, OrderedDict is a subclass of dictionary that remembers the order of the keys that were inserted. The only difference between OrderedDict() and the dict() lies in their handling of key order.
The standard dictionary does not guarantee any specific order when iterated whereas, the OrderedDict provides a specific order in which keys are added into the dictionary and maintain the same order when iterated.
SyntaxFollowing is the syntax of the Python OrderedDict() class −
collections.OrderedDict()Example
Following is an basic example of the Python OrderedDict() −
# A Python program to demonstrate working of OrderedDict from collections import OrderedDict od = OrderedDict() od['a'] = 1 od['b'] = 2 od['c'] = 3 od['d'] = 4 for key, value in od.items(): print(key,":",value)
Following is the output of the above code −
a : 1 b : 2 c : 3 d : 4defaultdict
The Python defaultdict() is a container, which is similar to the dictionaries. It is present in the collection module. It is a subclass of the dictionary class which returns a dictionary as object.
The functionality of the both dictionaries and defaultdict are similar, the only difference is the defualtdict does not raise a KeyError. It provides a default value for the key which does not exists.
SyntaxFollowing is a syntax of the Python defaultdict() class −
defaultdict(default_factory)Example
Following is an basic example of the Python defaultdict() class −
from collections import defaultdict def default(): return 'Key not found' dic1 = defaultdict(default) dic1[1] = 'one' dic1[2] = 'two' dic1[3] = 'Three' print(dic1) print(dic1[5])
Following is the output of the above code −
defaultdict(<function default at 0x000002040ACC8A40>, {1: 'one', 2: 'two', 3: 'Three'}) Key not foundUserDict
The Python Userdict() is a dictionary present in the collections module. It is a class acts as a wrappers around the dictionary objects. This class is useful when one wants to create a dictionary of their own with some modified functionality or with some new functionality.
It can be considered as adding new behaviour to the dictionary. This class takes a dictionary instance as an argument and simulates a dictionary that is kept in a regular dictionary. The dictionary is accessible by the data attribute of this class.
SyntaxFollowing is the syntax of the Python Userdict()−
collection.Userdict([data])Example
Following is a basic example of the Python Userdict() class −
from collections import UserDict dic = {'a':1,'b': 2,'c': 3,'d':4} # Creating an UserDict userD = UserDict(dic) print(userD)
Following is the output of the above code −
{'a': 1, 'b': 2, 'c': 3, 'd': 4}UserList
The Python UserList is a container like list present in collections module. This class acts as a wrapper class around the list objects. It is useful when one wants to create a list of their own with some modified functionality or with some new functionality. It can be considered as a way of adding new functionality for the list.
The UserList() takes a list instance as an argument and simulates a list that is kept in a regular list. The list is accessible by the data attribute of the this class.
SyntaxFollowing is the Syntax of the Python UserList class −
collections.UserList(data)Example
Following is an basic example of the Python UserList() −
# Python program to demonstrate # userlist from collections import UserList List1 = [10, 20, 30, 40] # Creating a userlist userlist = UserList(List1) print(userlist.data)
Following is the output of the above code −
[10, 20, 30, 40]UserString
The Python UserString is present in collections module. This is a class which acts as a wrapper class around a string. This class is useful to create a string of our own and can also modify the functionally of the methods and can also add new method to the class. It can be considered as a way of adding new behaviors for the string.
The UserString class takes any argument that can be converted to string and simulates a string whose content is kept in a regular string. The string is accessible by the data attribute of this class.
SyntaxFollowing is the syntax of the Python UserString −
collections.UserString(data)Example
Following is an basic example of the Python UserString class −
from collections import UserString data1 = [1,2,3,4] # Creating an UserDict user_str = UserString(data1) print(user_str) print("type :", type(user_str))
Following is the output of the above code −
[1, 2, 3, 4] type : <class 'collections.UserString'>
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4