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.
nums = [1,2,3,4,5] newList =  for i in nums: newList.append(i)
Now observe the code below which uses 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
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