The Pythonic way of implementation: List Comprehensions

Aqsa ShoebAqsa Shoeb
4 min read

If I tell you to square all the number in the given list in python. How will you code it? If you're a beginner in python, you'll probably do the following.

List = [5, 8, 3, 9, 11]

for i in range(len(List)):
    List[i] = List[i] ** 2

print("List after squaring each number:", List)

#Output
#List after squaring each number: [25, 64, 9, 81, 121]

There are some fancy ways of doing this, such as using map(). If you're not familiar with map() built-in function, it simply mean that you can apply a single specified function to all the elements of an iterable, such as the elements of a list. Let's understand how we can solve above stated problem using map().

def square(x):
    return x**2

numbers = [5, 21, 9, 42, 13]

squared_numbers = list(map(square, numbers))

print(squared_numbers)  

#Output
#[25, 441, 81, 1764, 169]

It's important to note that in Python 3, the map() function returns a map object, whereas in Python 2, it returns a list. In Python 3, if you need the result as a list, you explicitly convert it using list().

Now before we move to the actual topic of this article, that is list comprehension, let's go through one more way to solve this question, using Lambda function.

In Python, a lambda function, also known as an anonymous function or a lambda expression, is a concise way to create small, unnamed functions. The lambda keyword is used to define a lambda function. The basic syntax is as follows:

lambda arguments: expression

Arguments : The input parameters or variables on which the lambda function operates.

Expression : The single expression or operation that the lambda function performs.

Lambda functions are frequently used for quick, straightforward actions when it would be more laborious to define a whole function with the def keyword. They come in very handy when you need a function for just a short amount of time, like when you interact with higher-order functions like filter(), sorted(), and map() that need functions as parameters.

Let's see Lambda keyword in action

numbers = [10, 32, 37, 44, 5]

squared_numbers = list(map(lambda x: x**2, numbers))

print(squared_numbers)  

#Output
#[100, 1024, 1369, 1936, 25]

List Comprehensions

This is a beginner level tutorial, so we aren't diving deep to understand the usage of map() or lambda. We'll dive into lambda function and solve some problems through it in the next tutorial. Now let's understand the pythonic way of solving this simple problem.

original_list = [7, 24, 9, 19, 22]

squared_list = [x**2 for x in original_list]

print("Squared List:", squared_list)

#Output
#Squared List: [49, 576, 81, 361, 484]

Now you can compare all the approaches to solve this particular question, and would reach to the conclusion that list comprehension is a simple and efficient way to solve such questions.

Let's understand the syntax of writing list comprehension.

List comprehension is a concise way to create lists in Python. The basic syntax of list comprehension consists of square brackets [] containing an expression followed by a for clause. Optionally, you can include one or more if clauses to filter elements based on certain conditions. The general syntax is:

new_list = [expression for item in iterable if condition]

Expression : The operation to be performed on each item.

Item : The variable representing an element in the iterable.

Iterable : The sequence of elements to iterate over (e.g., a list, tuple, string).

Condition (optional): An optional filtering condition. The expression is applied only if the condition is true.

Let's see an example of list comprehension with condition,

numbers = [1, 2, 3, 4, 5] 
even_numbers = [x for x in numbers if x % 2 == 0]
# Output: [2, 4]

Even though, using list comprehensions has the same performance as using loops. The time complexity of using list comprehension is O(n). So performance wise, there's not much difference. But in terms of readability, list comprehensions are a better choice.

It is not necessary that all the time list comprehensions are better, or even though they are a pythonic way of writing python code, they are not always the most pythonic way of doing stuff.

It is possible that through nested list comprehensions, you may face a slower performance of the code or the readability of the code is poor.

You could also use other comprehensions such as set comprehensions or dictionary comprehensions to solve many problems along with list comprehensions. To understand this further, we'll solve some problems using list comprehensions and other comprehensions in coming articles.

The best way to learn about list comprehensions is to start implementing them in your code, projects, etc. Experimenting your way to learn something may take more time but it is a better way to grasp the concept and control over that concept.

If you like my tutorials or articles, consider supporting my work by simply following my page and provide your valuable feedback in the comments :)

Stay around for more beginner friendly python articles and tutorials. Let's grow together.

0
Subscribe to my newsletter

Read articles from Aqsa Shoeb directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aqsa Shoeb
Aqsa Shoeb