Working with python collections part 1

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:

  1. named tuple
  2. deque
  3. Counter
  4. OrderedDict
  5. 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[0], role[1] 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.

for example:

from collections import namedtuple
Company = namedtuple('Company', 'name location website')
mp = Company(name='micropyramid', location='hyderabad', website='')  or  Company('micropyramid', 'hyderabad', '')

now we can access it by the names like , mp.location ..etc

 >>> mp.location

We can create new object with the existing sequence(Company)

 >>> google = Company._make(['Google', 'hyderabad', ''])
 >>> google
      Company(name='Google', location='hyderabad', website='')

we can replace the values of the namedtuple by _replace() which returns a new object replacing specified fields with existing fields.

 >>> google._replace(location="Banglore")
     Company(name='Google', location='Banglore', website='')

we can also convert this namedtuple to dictionary by mp._asdict(), it gives an ordereddict. 

 >>> mp._asdict()
      OrderedDict([('name', 'micropyramid'), ('location', 'hyderabad'), ('website', '')])

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:

 from collections import deque
 dq = deque()
append items to deque:


 >>> dq
 deque(['a', 'b', 'c'])
pop elements from left:

 >>> dq.popleft()

 >>> dq

 deque(['b', 'c'])

append elements from left:

 >>> dq.appendleft()
 >>> dq
     deque(['a', 'b', 'c'])

we can specify the maximum length to deque by passing maxlen to it

 dq = deque(maxlen=10)

if we insert values after 10 ,the leftmost value will be poped out.

Append multiple values with extend():

 >>> dq.extend(['d', 'e', 'f'])
 >>> dq
    deque(['a', 'b', 'c', 'd', 'e', 'f'])
 >>> dq.extendleft([1,2,3])
 >>> dq
    deque(['3', '2', '1', 'a', 'b', 'c', 'd', 'e', 'f'])

deque is very useful to insert and delete elements fastly. But it is not recommended  for randomly accessing elements.

Posted On 22 January 2016 By MicroPyramid

Need any Help in your Project?Let's Talk

Latest Comments
Python Coding Techniques and Programming Practices

Coding techniques and programming practices are one of the features of a professional programmer. While writing code to solve a problem programmer should make simple ...

Continue Reading...
Python development environment on windows

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of ...

Continue Reading...
Sending SMS, MMS using Twilio.

A simple Tutorial on sending SMS and MMS in python using Twilio. In this tutorial you will learn how to send SMS, MMS and checking ...

Continue Reading...

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties