A.I, Data and Software Engineering

Advanced python: collections


In part 2, we introduced advanced python knowledge with built-in functions and other useful tools for sequence iteration, data transformation. Advanced python part 3 will continue with collections to manipulate our data.

Named tuple

Suppose we want to define a data structure to represent a geometric point on a typical x and y-axis. We could easily do this by defining a regular tuple with two elements, the x and y values of the point.

This may seem all fine and good, but as the program becomes more complex this kind of code easily loses its meaning and becomes hard to read.  Especially, if we don’t keep the names of all the point variables clear and meaningful. 

Namedtuples help to solve this problem by assigning meaning to each of the values along with the tuple itself. And they also provide some helpful functions for working with them. 

The operation over the namedtuple now become so much easier to read.

Default dict

Default dict can let you create a key that does not exist with some default value so that you don’t have to handle the key manually. The following code demonstrates a counter that will count the fruit of each type.


Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts and convenient for manipulating sequence with some basic statistics.

Deque (Double Ended Queue)

Deque (pronounced as /dek/) is used to append or pop data from either side, and they are designed to be memory-efficient when accessing them from either end (left and right). Deques can be initialized to be either empty or get their initial data from an existing, iterable object, and they can also be specified to have a maximum length.

You can read more advanced python with these articles.

Add comment

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Pin It on Pinterest


You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.