List Comprehensions in Python

List Comprehensions in Python are concise syntactic constructs. They can be used to generate lists from other lists by applying functions to each item in the list. In this article, I will introduce you to the concept of list comprehensions in Python.

List Comprehensions in Python

List comprehension creates a new list by applying an expression to each iterable element of the list. List comprehensions are one of Python’s most loved and unique features. The easiest way to understand them is probably to look at just a few examples:

Also, Read – 100+ Machine Learning Projects Solved and Explained.

squares = [n**2 for n in range(10)]

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Here’s how we would do the same without using a list comprehension:

squares = []
for n in range(10):

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

We can also add an if condition:

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
short_planets = [planet for planet in planets if len(planet) < 6]
['Venus', 'Earth', 'Mars']

Here is an example of filtering with an if condition and applying a transform to the loop variable:

loud_short_planets = [planet.upper() + '!' for planet in planets if len(planet) < 6]
['VENUS!', 'EARTH!', 'MARS!']

You can use the concept of a list comprehension to create compact readable programs. But when you have to choose, choose code that is easy for others to understand.

I hope you liked this article on List comprehension in Python programming language. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1538

Leave a Reply