8/22/2021

List Comprehension Python

30
  1. List Comprehension Python With Two Lists
  2. List Comprehension Python For Loop

A comprehension is a compact way of creating a Python data structure from iterators. With comprehensions, you can combine loops and conditional tests with a less verbose syntax.

Comprehension is considered more Pythonic and often useful in a variety of scenarios.

List Comprehension Python

List comprehensions are one of my favorite features in Python. I love list comprehensions so much that I’ve written an article about them, done a talk about them, and held a 3 hour comprehensions tutorial at PyCon 2018. List comprehension is a way to write logic inside a python list that perform a certain task. They are a beautiful way to create lists in python. General use of list compression in Python is to create a new list with an iterable base on some condition or logic. Here is a quick example to get all even numbers from a list using list comprehension. This adds the element to the end of the list. Looping method of Python program can be performed on multiple elements of a data list at the same time. List comprehensions are Python functions that are used for creating new sequences (such as lists, dictionaries, etc.) using sequences that have already been created.

What is List Comprehension?

List comprehension sounds complex but it really isn’t.

  1. What is List Comprehension? Often seen as a part of functional programming in Python, list comprehensions allow you to create lists with a for loop with less code. Let’s look at the following example. You create a list using a for loop and a range function.
  2. Here is an example that shows how conditionals can be written inside a list comprehension: X = 1.5, 2.3, 4.4, 5.4, 'n', 1.5, 5.1, 'a' # Original list # Extract non-strings from X to new list Xnonstr = el for el in X if not isinstance(el, str) # When using only 'if', put 'for' in the beginning.

List comprehension is a way to build a new list by applying an expression to each item in an iterable.

It saves you having to write several lines of code, and keeps the readability of your code neat.

Basic Example

Suppose you want to create a list of all integer square numbers from 0 to 4. You could build that list by appending one item at a time to an empty list:

Or, you could just use an iterator and the range() function:

Here both approaches produce the same result. However, a more Pythonic way to build a list is by using a list comprehension.

The general syntax for a list comprehension is:

Here’s how a list comprehension would build the above list:

In the example above, list comprehension has two parts.

The first part collects the results of an expression on each iteration and uses them to fill out a new list.

The second part is exactly the same as the for loop, where you tell Python which iterable to work on. Every time the loop goes over the iterable, Python will assign each individual element to a variable x.

More Examples

Below are few examples of list comprehension.

Example 1

List comprehensions can iterate over any type of iterable such as lists, strings, files, ranges, and anything else that supports the iteration protocol.

Here’s a simple list comprehension that uses string as an iterable.

Example 2

Following example applies abs() function to all the elements in a list.

Example 3

Following example calls a built-in method strip() on each element in a list.

Example 4

Following example creates a list of (number, square) tuples. Please note that, if a list comprehension is used to construct a list of tuples, the tuple values must be enclosed in parentheses.

Here’s why you should use list comprehension more often:

  • List comprehensions are more concise to write and hence they turn out to be very useful in many contexts.
  • Since a list comprehension is an expression, you can use it wherever you need an expression (e.g. as an argument to a function, in a return statement).
  • List comprehensions run substantially faster than manual for loop statements (roughly twice as fast). It offers a major performance advantage especially for larger data sets.

List Comprehension with if Clause

A list comprehension may have an optional associated if clause to filter items out of the result.

Iterable’s items are skipped for which the if clause is not true.

This list comprehension is the same as a for loop that contains an if statement:

Nested List Comprehensions

The initial expression in a list comprehension can be any expression, including another list comprehension.

For example, here’s a simple list comprehension that flattens a nested list into a single list of items.

Here’s another list comprehension that transposes rows and columns.

List Comprehension vs map() + lambda

List Comprehension Python With Two Lists

When all you’re doing is calling an already-defined function on each element, map(f, L) is a little faster than the corresponding list comprehension [f(x) for x in L]. Following example collects the ASCII codes of all characters in an entire string.

However, when evaluating any other expression, [some_expr for x in L] is faster and clearer than map(lambda x: some_expr, L), because the map incurs an extra function call for each element. Following example creates a list of all integer square numbers.

List Comprehension vs filter() + lambda

List comprehension with if clause can be thought of as analogous to the filter() function as they both skip an iterable’s items for which the if clause is not true. Following example filters a list to exclude odd numbers.

As with map() function, filter() is slightly faster if you are using a built-in function.

List Comprehensions and Variable Scope

In Python 2, the iteration variables defined within a list comprehension remain defined even after the list comprehension is executed.

For example, in [x for x in L], the iteration variable x overwrites any previously defined value of x and is set to the value of the last item, after the resulting list is created.

so, remember to use variable names that won’t conflict with names of other local variables you have.

Fortunately, this is not the case in Python 3 where the iteration variable remains private, so you need not worry.

  • Related Questions & Answers
  • Selected Reading
PythonServer Side ProgrammingProgramming

Python provides compact syntax for deriving one list from another. These expressions are called list comprehensions.List comprehensions are one of the most powerful tools in Python. Settembru . Python’s list comprehension is an example of the language’s support for functional programming concepts.

List Comprehension Python

The Python list comprehensions are a very easy way to apply a function or filter to a list of items. List comprehensions can be very useful if used correctly but very unreadable if you're not careful.

Syntax

The general syntax of list comprehensions is −

Above is equivalent to −

For example, say you want to compute the square of each number in a list. You can do this by providing the expression for your computation and the input sequence to loop over.

List Comprehension vs For Loop

Output

A better and faster way to write the above code is through list comprehension.

As we can see, writing the code using list comprehension is a lot more efficient, it's shorter and involves lesser elements.

List comprehensions vs lambda function

Unless you’re applying a single-argument function, list comprehensions are clearer than the map built-in function for simple cases. the map requires creating a lambda function for the computation, which is visually noisy.

Unlike map, list comprehensions let you easily filter items from the input list, removing corresponding outputs from the result.

ListPython

List comprehensions with conditional expression

For example, say you only want to compute the numbers less than 100, which are divisible by 2 and 5 both.

Take another example, where you only want to compute the squares of the numbers that are divisible by 2. Here, I do this by adding a conditional expression to the list comprehension after the loop −

Calculate even numbers between 1 to 100.

List Comprehension Python For Loop

List comprehensions are far faster than for loops when looping over a huge number of items. If readability alone isn't a convincing reason to use them as much as possible, speed should be.