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)]
squares

[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):
    squares.append(n**2)
squares

[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]
short_planets
['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]
loud_short_planets
['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.

Default image
Aman Kharwal

I am a programmer from India, and I am here to guide you with Data Science, Machine Learning, Python, and C++ for free. I hope you will learn a lot in your journey towards Coding, Machine Learning and Artificial Intelligence with me.

Leave a Reply