List comprehension
List comprehensions are elegant way to create new lists in Python. List comprehension are faster and more compact than normal functions and loops for creating list in Python.
Syntax of List Comprehension
[expression for item in list]
List Comprehension vs For Loop in Python
Suppose, we want to separate the letters of the word animal and add the letters as items of a list. The first thing that comes in mind could be using for loop.
Example 1: using for loopletters = []
for i in 'animal':
letters.append(i)
print(letters)
When we run the program, the output will be:
['a', 'n', 'i', 'm', 'a', 'l']
Python has an easier way to solve this issue using List Comprehension.
Example 2: using list comprehensionletters = [ letter for letter in 'animal' ]
print(letters)
In the above example, a new list is assigned to variable letters
, and list contains the items of the iterable string 'animal'. We call print()
function to receive the output.
List comprehension is generally more compact and faster than normal functions and loops for creating list.