DEV Community

Cover image for List Comprehension in Python
Syed Faysel Ahammad Rajo
Syed Faysel Ahammad Rajo

Posted on

List Comprehension in Python

What is List Comprehension?

List comprehension is nothing just a shorter way to create a list from another list or iterable instead of using an actual loop or something else. Hence, it list comprehension makes the code or syntax shorter and clean.

The code below is a very basic example of list comprehension.

Creating a list from another list using loop

nums = [1,2,3,4,5]
newList = []
for i in nums:
    newList.append(i)
Enter fullscreen mode Exit fullscreen mode

Now observe the code below which uses list comprehension

Creating a list from another list using list comprehension

nums = [1,2,3,4,5]
newList = [i for i in nums]
Enter fullscreen mode Exit fullscreen mode

That's it. See, how shorter the code is. Now, let's explain what happened here. The first 'i' inside the newList is the item to be append, and the next part for i in nums is simply nothing but a loop. This portion of code iterates over the list nums. Then each item is added to the newList.

Even we can make list comprehension more complex. We can use expression, condition in this comprehension.

Like the following example. Let's say we want a list containing the elements which are the squared of even elements from another list.

Hence the code looks like this:

nums = [1,2,3,4,5]
newList = [i**i for i in nums if i%2==0]
Enter fullscreen mode Exit fullscreen mode

See, How simple! List comprehension comes handy. It saves much time & keeps the code clean. Python programmer should utilize the benefits of list comprehension.

Thanks for reading. Hope this article makes you understood list comprehension.
My website: Syed Faysel

Top comments (1)

Collapse
 
miafelsey profile image
John Donne

List comprehension is a simple way to make lists of values, or sequences, and it's great for quickly generating large lists.This works because we've used the default generator function in Python. A generator function returns new values one at a time as each element is requested from the list. I will ask for more info about essay writer. In this case, we're using a simple generator function that returns an integer value and then stops. We could have used any other type of generator function (like the built-in range() function), but we'll stick with the simplest example here so we can focus on what makes list comprehensions special.