List Comprehensions in Python

A Complete Guide to using List Comprehensions in Python, its uses and benefits over standard loops

Chaitanya Baweja
The Startup

--

Photo by Kevin Ku on Unsplash

Beautiful is better than ugly, Flat is better than nested

The Zen of Python beautifully sums up everything there is to know about programming style.

List comprehensions in python takes this idea further by providing an elegant way of creating lists based on another list or iterator.

To better understand this concept, let’s begin with a straightforward example.

Suppose you wish to find cube of all numbers in a list and store them in a new list. Using a for loop, we can code this as follows:

However, Python provides an easier and more elegant way to solve this problem using List Comprehension.

--

--

Chaitanya Baweja
The Startup

Machine Learning Engineer | Python | Data Analytics | Economics | Physics