Collections are the most useful high-performance container data types in python. collections module provides the datatypes alternative to dict, list, set and tuple for better performance.
The following are the data types provided by collections module:
- named tuple
- default dict
Working with namedtuple:
Most of us already know about tuples in python. A tuple is a lightweight object type which allows to store a sequence of immutable Python objects.
for example: role = ('developer', 'designer', 'tester')
here we need to use the integer indexes to access the elements in the tuple like role, role which gives 'developer' and 'designer' as the results respectively.
but in the case of namedtuple we have tuple name and tuple field names to access the tuples by their names.
now we can access it by the names like mp.name , mp.location ..etc
We can create new object with the existing sequence(Company)
we can replace the values of the namedtuple by _replace() which returns a new object replacing specified fields with existing fields.
we can also convert this namedtuple to dictionary by mp._asdict(), it gives an ordereddict.
the main advantage of namedtuple is to understand the code easily, it is faster than dictionary and it doesn't require more space than tuples.
unlike dict we get the items in the order we defined the fields in namedtuple.
Working with Deque:
Deque is double-ended queue which allows us to append and pop the elements from both sides of the queue. It is thread safe and memory efficient.
We can also specify the maximum length that a deque can hold. If the number of elements exceeds the maximum length it simply pop the items from the other side.
to instantiate Deque object:
append elements from left:
we can specify the maximum length to deque by passing maxlen to it
if we insert values after 10 ,the leftmost value will be poped out.
Append multiple values with extend():
deque is very useful to insert and delete elements fastly. But it is not recommended for randomly accessing elements.