List Comprehension in Python

List comprehension in Python offers a powerful way to create and manipulate items in a list or any other sequence in a single line of code.

Naturally, you can simply create a list by assigning a variable to a list object or append items to an empty list in the course of an iteration or looping.

#option 1
L = ['apple', 'orange', 'mango']

#option 2
#create an empty list
L = []

#append items to it
L.append('apple')
L.append('orange')
L.append('mango')

print(L)

#output
['apple', 'orange', 'mango']

Aside from these, you can also make use of list comprehension to create lists on the fly.

List comprehension offers a simple and powerful way of creating a list from another list or any other sequence.

With a single line of code, you can be able to achieve amazing functionality.

Creating a list with list comprehension

In order to appreciate list comprehensions, let’s create a list of numbers from 1 – 10 using the for loop.

L = []

for num in range(1, 11):

    L.append(num)

print(L)

#output

#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In the example above, we created an empty list and added items to it using the append method and the for loop.

However, you can easily achieve the same outcome with just a single line of code using the list comprehension as shown below:


result = [num for num in range(1,11)]

print(result)

#output

#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

List comprehensions are not only simpler and easier to read than the loop construct but faster in execution.

Now, let’s explain the syntax for list comprehension.

List comprehension: Syntax explained

List comprehension is essentially a single-line statement enclosed inside a square bracket.

A list comprehension defines an expression containing a variable which is a member of an iterable or sequence. To explain further, let’s use list comprehension to create a list of squares of numbers from 1 – 5.

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

squares = [num**2 for num in L]

print(squares)

#output

#[1, 4, 9, 16, 25]

In the above example, num**2 is an expression and num is a variable which is a member of the list L, which is iterable.

As simple as it looks, list comprehension is can be used to perform powerful operations on a sequence.

However, you should never abuse it by writing simple and incomprehensible codes. The essence of list comprehension is achieving simple and easy-to-read codes, so don’t overuse them.

Applying conditionals in a list comprehension

As stated earlier, list comprehension allows you to create a list easily. It also allows you to use conditional logic (if and else conditionals) to alter the outcome of the newly created list.

For instance, you can use list comprehension to create a list containing only even numbers from a list of natural numbers.


L = [1,2,3,4,5,6,7,8,9,10]

numbers = [num for num in L if num % 2 == 0]

print(numbers)

#output

#[2, 4, 6, 8, 10]

In the same vein, we can create a new list to contain only odd numbers as shown below:


numbers = [num for num in L if num % 2 != 0]

print(numbers)

#output

#[1, 3, 5, 7, 9]

You can also decide to filter out values from the new list so that only numbers that are greater than 1 are used as shown below:


result = [num*2 for num in range(4) if num > 1]

print(result)

#output

#[4, 6]

Creating a list of characters in a string

So far, we have been giving examples with numbers and operations with list comprehension are not limited to numbers.

You can also use list comprehension to create a list of all the characters in a given string.


chars = [char for char in 'hello']

print(chars)

#output

#['h', 'e', 'l', 'l', 'o']

Using list comprehension to create nested lists

Let’s say that you want to create a list containing a list of numbers and their respective squares. The example below demonstrates how to do so with a list comprehension.


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

squares = [[num, num**2] for num in L]

print(squares)

#output

#[[1, 1], [2, 4], [3, 9], [4, 16], [5, 25]]

Nested comprehension

A nested comprehension is like a comprehension inside another comprehension.

Let’s take a look:


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

result = [[x[i] for x in L] for i in range(2)]

print(result)

#output

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

Using map, zip and filter functions with list comprehensions

You can utilize in-built functions like map(), zip() and filter() in a list comprehension to achieve even more sophisticated outcomes.

map() function

This is how the map() function works.

It performs a given action on all the elements of an iterable and returns the result as an iterable.

Let’s say that you want to square all the items in a list.

The map function requires that you provide a function that calculates squares and a list upon which the items will be squared.

To demonstrate this, we will be making use of the in-built trunc() function as shown below to remove all the decimal parts of numbers in the list.


L = [1.2,2.88,3.01,4.00,5.75]

num = map(trunc, L)

print(num)

#output

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

Also, you can use the map function alongside the abs() function to remove all the signs (negative and positive) in numbers in a list.


num = map(abs, [-1,-2,-3,-4])

print(num)

#output

#[1, 2, 3, 4]

Map with user-defined functions

Apart from the standard in-built functions, you can also use custom-defined functions with map().

Let’s create a function that computes the square of any number.


def square(num):

    return num**2

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

squares = map(square, L)

print(squares)

#output

#[1, 4, 9, 16, 25]

Apart from the regular functions, you can also use lambda functions with map function

Using lambda functions with map

The Lambda function is simply a function without a name or rather an anonymous function. It’s a way of creating a function on the fly without the need for defining and calling on a function.

To use a lambda function in a map, simply use the lambda function in place of the argument for the function in the map.

For example:

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

squares = map(lambda num: num**2, L)

print(squares)

The above code makes use of the lambda function instead of the regular functions as we did in the previous example.

Using map() with list comprehensions

Now, let’s take a look at how we can use the map function with list comprehension.

The following examples combined the functionalities of both the map and list comprehension.

The example below makes use of map and list comprehension to create a list of squares, of items of another list.


def square(num):

    return num**2

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

result = [num for num in map(square, L)]

print(result)

#output

#[1, 4, 9, 16, 25]

Even though the above outcome can be achieved with only list comprehension alone, the essence is to show you that both can be used to accomplish sophisticated results.

zip() function

The zip function combines two lists together. This function creates a new list with items as tuples containing items in the same positions in their respective lists.

For instance:


L1 = [1,2,3]

L2 = [4,5,6]

result = zip(L1, L2)

print(result)

#output

#[(1, 4), (2, 5), (3, 6)]

You can combine as many lists as possible using the zip function as shown below:


L1 = [1,2,3]

L2 = [4,5,6]

L3 = [7,8,9]

L4 = [10,11,12]

result = zip(L1, L2, L3, L4)

print(result)

#output

#[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]

Combining lists of variable lengths with zip

You can combine lists of different lengths with the zip() function.

However, the new list will have a length like that of the shortest list being zipped.

Hence, items in positions greater than that in the last item in the shortest list will be ignored or not be included in the new list.


L1 = [1,2,3]

L2 = [4,5]

L3 = [7,8,9]

result = zip(L1, L2, L3)

print(result)

#output

#[(1, 4, 7), (2, 5, 8)]

Now, let’s use create a list using the zip function.


L1 = [1,2,3]

L2 = [4,5,6]

result = [x for x in zip(L1, L2)]

print(result)

#output

#[(1, 4), (2, 5), (3, 6)]

Supposed you want the newly created list to contain a list of zip items instead of tuples, below will give you that outcome.


result = [[x,y] for [x,y] in zip(L1, L2)]

print(result)

#output

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

Now, let’s make use of the map and zip in a list comprehension to create something powerful.

We will be combining two lists together using the zip function and then using the map function to sum the elements in the respective tuples in the newly created list.


L1 = [1,2,3]

L2 = [4,5,6]

result = [num**2 for num in map(sum, zip([1,2,3], [2,3,4]))]

print(result)

#output

#[9, 25, 49]

filter() function

The filter() function just like the map() function requires a function as an argument. The map function iterates over all the items in the iterable and at the same time performs a function call using the items as an argument and returning the result.

On the other hand, the filter() function performs conditional operations on the items in the iterable with the aim to return or retain the various items in the list being created.

For example, let’s use the filter() function to create a list with all the items as even numbers.


L = [1,2,3,4,5,6,7,8,9,10]

def is_even(num):

    if num%2 == 0:

        return True

result = filter(is_even, L)

print(result)

#output

#[2, 4, 6, 8, 10]

You can also use the Lambda function as with the zip() function as shown below:


L = [1,2,3,4,5,6,7,8,9,10]

result = filter((lambda x: x % 2 == 0), L)

print(result)

#output

#[2, 4, 6, 8, 10]

 

Leave a Reply

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