How to use List Comprehension in Python?

How to use List Comprehension in Python?

By Amit Kumar1 | WayOfCoding | 30 Jul 2021


Hi Guys,

In this tutorial I'm going to cover:
    1. What is List Comprehension?
    2. Advantages of List Comprehension.
    3. How to understand and write efficient List Comprehension (we will mostly focus here).

 

1.What is List Comprehension?

List Comprehension is a one-liner syntax in python that is used to generate a list (from another iterable object like list, set, dict, etc., or a sequence) in a more efficient and faster manner than the traditional for loop.

 

2.Advantages of List Comprehension.

> Saves multiple lines of code.
> Faster than traditional for loop.
> Simplifies the codebase.


3.How to understand and write efficient List Comprehension.

-List Comprehension opens and closes with square brackets "[]" (a list as an output).
-Inside the square bracket there are 2 parts:
    1. Expression
    2. Sequence of for's and if's.

Let understand both parts.

list comp

If you see it in the image. you can see that Expression is nothing but the area 1 where x is.
In the above example, we are not performing any activity on the elements of the list, we are just returning as it is.

Let's see what we can do here.

Code:

quantity = [100,120,90,70,110]

# let's say we want to add/substract/divide/multiply some value to each element of quantity list.
print([x+5 for x in quantity])
print([x*5 for x in quantity])
print([x-5 for x in quantity])
print([x/5 for x in quantity])

Output:

[105, 125, 95, 75, 115]
[500, 600, 450, 350, 550]
[95, 115, 85, 65, 105]
[20.0, 24.0, 18.0, 14.0, 22.0]

Not just arithmetic operations but we can all sorts of one-liner operations here on each element.

now let's come to the second part of the List Comprehension.
- it can have multiple for and if conditions
- for is used to iterate through given iterable objects.

temp_list=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
print([x for x in temp_list if x>10])

here for x in temp_list is used to iterate through the temp_list.

- if is used to filter the items from the original iterable object mentioned in the for statement.

output:

[11, 12, 13, 14, 15, 16, 17, 18, 19]

here if x>10 is the condition and it returns the element of the list only if the condition is satisfied.

- we can also have nested List Comprehension.

Example:
suppose we have a list of lists.

a=[['a','b','c'],['x','z'],['q','w','e']]

 

and we want to perform some operation (say, converting to upper case) on each element of the inner list.

Normally:

for idx,item in enumerate(a):
    for s_idx,sub_item in item:
        a[idx][s_idx]=sub_item.upper()

using List Comprehension:

a=[[subitem.upper() for subitem in item] for item in a]

 

output:
[['A', 'B', 'C'], ['X', 'Z'], ['Q', 'W', 'E']]


Here are some more examples for you to explore:

# we can perform all sorts of operations here:
# few examples on the list of strings:
# let's say you have a name list.
names=[' Amit','ameet ','']

# suppose you want to clean(remove extra spaces) the list, convert to title case (first letter of each word as capital), and remove empty strings.
# traditionally you would create a new list.
temp_list=[]
# loop over the original list.
for an item in names:
    # check if string is not empty
    if item.strip():
        '''
        1.Remove extra spaces.
        2.Convert to title case.
        3.append to a temporary list.
        '''
        temp_list.append(item.strip().title())

# updated back the original list.
names=temp_list

print(names)

# Now let's see how we can do all of these in using list comp.

# Approach 1:
# create a function that takes a string and performs some operation.
def complex_ops(item):
    '''
    1.Remove extra spaces.
    2.Convert to title case.
    3.return the string
    '''
    item=item.strip()
    item=item.title()
    return item


names=[' Amit','ameet ','']
# now call the function for each element in the list which is not empty
names=[complex_ops(x) for x in names if x.strip()]
print(names)

# Approach 2:
# Do everything in the list comp.
names=[' Amit','ameet ','']
names=[x.strip().title() for x in names if x.strip()]
print(names)

 

 

How do you rate this article?


3

0

Amit Kumar1
Amit Kumar1

Hi All, My name is Amit, I'm a software engineering, who loves to solve programming scenarios and automate stuff using Python/Shell Scripting or any other language :P (pun of being a polyglot). Join Publish0x. https://www.publish0x.com?a=w9aAP28Pev


WayOfCoding
WayOfCoding

Let's learn together. Donate ETH here: 0x21DfffFB92B42721FC87c9b70773306023dA843B

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.