Python List Comprehension – Time to upskill your programming

In today’s article, we are going to discuss a very important topic, that is, Python list comprehension. It is a very powerful way to perform complex operations and manipulate iterables.

First, we will take a quick look at lists and then move towards the list comprehension. We will see various ways of how you can use list comprehension and become a better programmer.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What are Lists?

Lists are a mutable collection of elements. They can be of any type like strings, numbers, sets, booleans, etc. They are created by using square brackets.

Code:

List = [1, 2, 3, ”AB”, “DC”]

We can access them with indexes starting from zero. It also supports slicing.

Code:

print(List[1])
print(List[1:3])

Output:

2
[2, 3]

So, before moving ahead, have a detailed look of Python Lists with TechVidvan.

Python List comprehension

List comprehensions are an easy, concise, and fast way to build lists. It allows you to perform complex operations on lists easily using a single line.

First, observe this code.

Suppose you want to iterate over a list, check a condition and then manipulate it with expression and append the result in a new list. The code will look something like this.

Code:

new_list = []
for i in old_list:
    if filter(i):
        new_list.append(expressions(i))

But with Python list comprehension, we can do this in one line.

Code:

new_list = [ expressions(i) for i in old_list if filter(i) ]

Once you understand this, it will be a lot easier to code this way.

Syntax:

[ expression for item in list if conditional ]

How you can Use Python List Comprehension

1. Simple List Comprehension

Simple use of a Python list comprehension is when you want to iterate over a list and perform a quick operation on the elements.

Code:

nums = [1,2,3,4,5]

new_nums = [ i+10 for i in nums]
power_nums = [i**2 for i in nums]

print(new_nums)
print(power_nums)

Output:

[11, 12, 13, 14, 15]
[1, 4, 9, 16, 25]

2. List Comprehension with Conditions

List comprehensions also provide a way to check for conditions and filter out the elements you don’t need from the list.

Code:

nums = [1, 12, 8, 14, 9, 23, 36, 5, 4 ]

greater_ten = [i for i in nums if(i>10)]
evens = [i for i in nums if(i%2==0)]

print(“Greater than ten :”,greater_ten)
print(“Even numbers list :”,evens)

Output:

Greater than ten : [12, 14, 23, 36]
Even numbers list : [12, 8, 14, 36, 4]

3. List Comprehension with Nested Conditions

Till now, in Python list comprehension, we have seen simple conditions but what about some nested conditions? Let’s see how we can use nested conditions in a list comprehension.

Code:

print([i for i in range(100) if(i%2==0) if(i%5==0) ])

Output:

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

Here, we used two conditions separated by space. It works by first checking the first condition and filters out the numbers that are divisible by 2 and then from those numbers, it will filter out the numbers divisible by 5.

4. If-else Condition in List Comprehension

Let us see how we can use the if-else statements in a Python list comprehension. If-else conditions are very useful and widely used, using them in list comprehensions will make it even more powerful.

Code:

print([ x+1 if(x%2==0) else x**2 for x in [1,2,3,4,5,6,7,8] ])

Output:

[1, 3, 9, 5, 25, 7, 49, 9]

Here, we use the if-else statement in the first position and we incremented one to even numbers and squared the odd numbers. List comprehensions make this an easy task.

5. Nested List Comprehension

Suppose you have a list like this:

Code:

List = [[1,2,3], [4,5,6], [3,4] ]

Now to iterate over each element, we will have to nest inside the list comprehension.

Code:

[ res for x in List for res in x]

Output:

[1, 2, 3, 4, 5, 6, 3, 4]

For understanding purposes, you can think of this statement as:

Code:

for x in List:
  for res in x:
    print(res)

This way we can flatten a nested list.

So far, we were discussing list comprehensions in Python but now we can see similar comprehension techniques in the dictionary, sets, and generators.

Python Dictionary Comprehension

Python allows us to create dictionary comprehensions. The syntax is similar to list comprehensions in Python.

Syntax:

{key: expression(i) for (key, i) in iterable}

Code:

num=[1,2,3,4]
name=['one','two','three','four']

my_dict = {num:name for (num,name) in zip(num,name)}
print(my_dict)

Output:

{1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’}

You can also use list comprehensions to create dictionary comprehensions.

Code:

even_squares = {x: x**2 for x in range(0,12,2)}
print(even_squares)

Output:

{0: 0, 2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

Python Sets Comprehension

Lets us now see how sets comprehensions work.

Syntax:

{ expression(i) for i in iterable condition }

Code:

odd = { num for num in [1,2,3,4,5,6] if num%2==1}
print(odd)

Output:

{1, 3, 5}

Python Generator Comprehensions

A quick way to create generators is with generator comprehensions.

Syntax:

(expression(i) for i in iterable)

Code:

gen = (x**2 for x in range(100))
print(gen)
next(gen)
next(gen)
next(gen)
next(gen)

Output:

<generator object <genexpr> at 0x000001EA897B0BA0>
0
1
4
9

Summary

This was all about the Python list comprehensions. Now you can clean up your code by writing simple and concise code. You can easily modify lists using list comprehensions.

You should use list comprehensions in Python more often whenever possible but make sure not to write lengthy list comprehensions, then it would be better to use for loops.

I hope you learned new things with TechVidvan’s Python lists comprehension article. If you have any doubts, mention in the comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.