List Comprehension in Python
Syed Faysel Ahammad Rajo
Posted on September 14, 2022
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)
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]
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]
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
Posted on September 14, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.