Python List Comprehension

Creating a list in Python:

Before we move into the topic “Python list comprehension”, let’s see the most popular ways with which we create lists in Python.

For loop:

Below are the steps to create a list using for loop.

  • Declare an empty list.
  • Iterate through an iterable using a loop.
  • Append the elements to the declared empty list.
st='hello world'
l=[]
for i in st:
    l.append(i)
print(l)
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

map():

The map() function takes an iterable and function as an argument. Each item of an iterable is passed to the function. The result of the map() function is an iterable map object, which we can convert to a list using the list() function.

syntax:

map(function,iterable)

Example:

def square(n):
    return n*n

l=[7,14,6,15,2,9]
ob=map(square,l)
print(ob)
print(list(ob))
<map object at 0x04A93510>
[49, 196, 36, 225, 4, 81]

List Comprehension:

List comprehension is another elegant, short and concise way to create lists in Python.

Syntax:

[expression for item in iterable]

Example:

Let’s rewrite the for loop from the first example with a list comprehension. It will be just a single line of code.

output_list=[i for i in 'hello world']
print(output_list)
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

However, not every for loop can be rewritten as a list comprehension. Once you become comfortable, with list comprehension you can replace more for loops with it.

Conditions in Python list Comprehension:

We can also use conditions in a list comprehension.

If:

The below program prints only the vowels in a given string.

vowels=['a','e','i','o','u']

output_list=[i for i in 'hello world' if i.lower() in vowels]
print(output_list)
['e', 'o', 'o']

If else:

vowels=['a','e','i','o','u']

output_list=["Vowel" if i.lower() in vowels else "Consonant" for i in 'hello world' ]
print(output_list)
['Consonant', 'Vowel', 'Consonant', 'Consonant', 'Vowel', 'Consonant', 'Consonant', 'Vowel', 'Consonant', 'Consonant', 'Consonant']

Nested if:

The below program prints only the upper case vowels.

vowels=['a','e','i','o','u']

output_list=[i for i in 'hEllo wOrld' if i.lower() in vowels if i not in vowels]
print(output_list)
['E', 'O']

Here we are checking for two things:

  • Checks for each character in a string whether it’s a vowel or not.
  • If the above condition is satisfied, then check if it’s an upper case vowel.

Nested for loop in Python list comprehension:

We can rewrite not only the for loops but also nested for loops as a list comprehension. Let’s try to understand with an example. We have an input list of strings. The output list contains the characters of each string.

The code using nested for loop will be:

st=['hello','world','hi']

output_list=[]

for i in st:
    for j in i:
        output_list.append(j)

print(output_list)
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', 'h', 'i']

We can rewrite the above code as list comprehension in a single line.

st=['hello','world','hi']

output_list=[j for i in st for j in i]
print(output_list)
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', 'h', 'i']

Reference

Translate ยป