List Comprehension An Overview

Ranjit Kumar Pattnayak
2 min readOct 9, 2019

--

List comprehensions are very widely used in python. They are an elegant way to define and create a list in python.

Let's say that you have a list of numbers and you want to create a new list of numbers that’s the same as the old list, except that each number has 1 add to it. We can do that in two ways using for loop and list comprehension.

First, let’s talk about how we can do that using for loop. To do so we can initialize a new empty list, loop through the old list, add 1 to each entry and append all new values to the new list.

Using for loop

But for loops are inefficient both computationally and in terms of coding time and space, particularly when we can do all this in a single line of code. Hence list comprehension comes into the picture. List comprehension is used when there are multiple variables.

Using List Comprehension

List comprehension can be written not just only on list but even range. Basically list comprehension uses a single line of code instead of for loops that use multiple lines.

List comprehensions can only be written only on an iterable or iterators. They consist of the output expression and they can also consist the conditions-the if-else conditions.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ranjit Kumar Pattnayak
Ranjit Kumar Pattnayak

No responses yet

Write a response