Extra particular options in Python


Python is an superior programming language! It is among the hottest languages for growing AI and machine studying functions. With an easy to be taught syntax, Python has some particular options that distinguish it from different languages. On this tutorial, we’ll discuss some particular attributes of the Python programming language.

After finishing this tutorial, you’ll know:

  • Constructs for checklist and dictionary comprehension
  • Learn how to use zip and enumerate features
  • What are operate contexts and interior designers
  • What’s the function of mills in Python

Let’s get began.

Python Particular Options
Photograph by M Mani, some rights reserved.

Tutorial Overview

This tutorial is split into 4 components; they’re:

  1. Listing and dictionary comprehension
  2. Zip and enumerate features
  3. Perform contexts and interior designers
  4. Turbines in Python with instance of Keras generator

Import Part

The libraries used on this tutorial are imported within the code under.

Listing Comprehension

Listing comprehension gives a brief, easy syntax for creating new lists from current ones. For instance, suppose we require a brand new checklist, the place every new merchandise is the previous merchandise multiplied by 3. One technique is to make use of a for loop as proven under:

The shorter technique utilizing checklist comprehension requires solely a single line of code:

You’ll be able to even create a brand new checklist primarily based on a particular criterion. For instance, if we wish solely even numbers added to the brand new checklist.

It’s also doable to have an else related to the above. For instance, we will depart all even numbers intact and change the odd numbers by zero:

Listing comprehension can even used to switch nested loops. For instance the next:

will be carried out as follows, with two “for” contained in the checklist comprehension:


Syntax for checklist comprehension is given by:

newlist = [expression for item in iterable if condition == True]


newList = [expression if condition == True else expression for item in iterable]

Dictionary Comprehension

Dictionary comprehension is just like checklist comprehension, besides now we’ve (key, worth) pairs. Right here is an instance; we’ll modify every worth of the dictionary by concatenating the string ‘quantity ‘ to every worth:

Once more, conditionals are additionally doable. We will select so as to add (key, worth) pairs primarily based on a criterion within the new dictionary.

Enumerators and Zip in Python

In Python an iterable is outlined as any knowledge construction that may return all its objects, one by one. This manner you should use a for loop for additional processing of all objects one after the other. Python has two further constructs that make for loops simpler to make use of, i.e., enumerate() and zip().


In conventional programming languages, you want a loop variable to iterate by means of completely different values of a container. In Python that is simplified by providing you with entry to a loop variable together with one worth of the iterable object. The enumerate(x) operate returns two iterables. One iterable varies from 0 to len(x)-1. The opposite is an iterable with worth equal to objects of x. An instance is proven under:

By default, enumerate begins at 0 however we will begin at another quantity if we specified it. That is helpful in some state of affairs, for instance:


Zip permits you to create an iterable object of tuples. Zip takes as argument a number of containers $(m_1, m_2, ldots, m_n)$, and creates the i-th tuple by pairing one merchandise from every container. The i-th tuple is then $(m_{1i}, m_{2i}, ldots, m_{ni})$. If the handed objects have completely different lengths, then the entire variety of tuples fashioned have a size equal to the minimal size of handed objects.

Under are examples of utilizing each zip() and enumerate().

Perform Context

Python permits nested features, the place you possibly can outline an inside operate inside an outer operate. There are some superior options associated to nested features in Python.

  • The outer operate can return a deal with to the inside operate
  • The inside operate retains all its atmosphere and variables native to it and in its enclosing operate even when the outer operate ends its execution.

An instance is given under with rationalization in feedback.

Decorators in Python

Decorators are a robust characteristic of Python. You should use decorators to customise the working of a category or a operate. Consider them as a operate utilized to a different operate. Use the operate identify with @ image to outline the decorator operate on the embellished operate. The decorator takes a operate as argument, giving quite a lot of flexibility.

Take into account the next operate square_decorator() that takes a operate as an argument, and likewise returns a operate.

  • The inside nested operate square_it()takes an argument arg.
  • The square_it()operate applies the operate to arg and squares the outcome.
  • We will cross a operate corresponding to sin to square_decorator(), which in flip would return $sin^2(x)$.
  • You may as well write your individual custom-made operate and use the square_decorator() operate on it utilizing the particular @image as proven under. The operate plus_one(x) returns x+1. This operate is embellished by the square_decorator() and therefore, we get $(x+1)^2$.

Turbines in Python

Turbines in Python can help you generate sequences. As an alternative of writing a return assertion, a generator returns a number of values by way of a number of yield statements. The primary name to the operate returns the primary worth from yield. The second name returns the second worth from yield and so forth.

The generator operate will be invoked by way of subsequent().Each time subsequent() is known as the following yield worth is returned. An instance of producing the Fibonacci sequence up until a given quantity x is proven under.

Instance of Information Generator in Keras

One use of generator is the information generator in Keras. The rationale it’s helpful is that we don’t need to hold all knowledge in reminiscence however need to create it on the fly when the coaching loop wants it. Bear in mind in Keras, a neural community mannequin is educated in batches, so a generator are to emit batches of information. The operate under is from our earlier submit “Utilizing CNN for monetary time collection prediction“:

The operate above is to choose a random row of a pandas dataframe as a place to begin and clip subsequent a number of rows as one time interval pattern. This course of is repeated a number of occasions to gather many time intervals into one batch. Once we collected sufficient variety of interval samples, on the second final line within the above operate, the batch is dispatched utilizing the yield command. As it’s possible you’ll already observed, generator features should not have return assertion. On this instance, the operate even will run eternally. That is helpful and essential as a result of it permits our Keras coaching course of to run as many epoch as we wish.

If we don’t use generator, we might want to convert the dataframe into all doable time intervals and hold them within the reminiscence for the coaching loop. This will likely be quite a lot of repeating knowledge (as a result of the time intervals are overlapping) and takes up quite a lot of reminiscence.

As a result of it’s helpful, Keras has some generator operate predefined within the library. Under is an instance of ImageDataGenerator(). We now have loaded the cifar10 dataset of 32×32 pictures in x_train. The information is linked to the generator by way of circulation() technique. The subsequent() operate returns the following batch of information. Within the instance under, there are 4 calls to subsequent(). In every case 8 pictures are returned because the batch dimension is 8.

Under is all the code that additionally shows all pictures after each name to subsequent().

Additional Studying

This part gives extra sources on the subject in case you are trying to go deeper.

Python Documentation


API Reference


On this tutorial, you found particular options of Python

Particularly, you discovered:

  • The aim of checklist and dictionary comprehension
  • Learn how to use zip and enumerate
  • Nested features, operate contexts and interior designers
  • Turbines in Python and the ImageDataGenerator in Python

Do you’ve got any questions on Python options mentioned on this submit? Ask your questions within the feedback under and I’ll do my finest to reply.



Leave a Reply

Your email address will not be published. Required fields are marked *