How do you use list comprehension?

When to Use a List Comprehension in Python

by James Timmins basics python

Mark as Completed

Tweet Share Email

Table of Contents

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Understanding Python List Comprehensions

Python is famous for allowing you to write code that’s elegant, easy to write, and almost as easy to read as plain English. One of the language’s most distinctive features is the list comprehension, which you can use to create powerful functionality within a single line of code. However, many developers struggle to fully leverage the more advanced features of a list comprehension in Python. Some programmers even use them too much, which can lead to code that’s less efficient and harder to read.

By the end of this tutorial, you’ll understand the full power of Python list comprehensions and how to use their features comfortably. You’ll also gain an understanding of the trade-offs that come with using them so that you can determine when other approaches are more preferable.

In this tutorial, you’ll learn how to:

  • Rewrite loops and map() calls as a list comprehension in Python
  • Choose between comprehensions, loops, and map() calls
  • Supercharge your comprehensions with conditional logic
  • Use comprehensions to replace filter()
  • Profile your code to solve performance questions

Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.

Python - List Comprehension

❮ Previous Next ❯


List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

Example:

Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.

Without list comprehension you will have to write a for statement with a conditional test inside:

Example

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)

Try it Yourself »

With list comprehension you can do all that with only one line of code:

Example

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

Try it Yourself »



Python – List Comprehension

  • Difficulty Level : Medium
  • Last Updated : 21 Oct, 2021

Python is renowned for encouraging developers and programmers to write efficient, easy-to-understand, and almost as simple-to-read code. One of the most distinctive aspects of the language is the python list and the list compression feature, which one can use within a single line of code to construct powerful functionality.

List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.

Syntax:

newList = [ expression(element) for element in oldList if condition ]

Python Lists

Lists are one of the four built-in data structures in Python. Other data structures that you might know are tuples, dictionaries, and sets. A list in Python is different from, for example, int or bool, in the sense that it's a compound data type: you can group values in lists. These values don't need to be of the same type: they can be a combination of boolean, String, integer, float values.

List literals are a collection of data surrounded by brackets, and the elements are separated by a comma. The list is capable of holding various data types inside it, unlike arrays.

For example, let's say you want to build a list of courses then you could have:

courses = ['statistics', 'python', 'linear algebra']

Note that lists are ordered collections of items or objects. This makes lists in Python "sequence types", as they behave like a sequence. This means that they can be iterated using for loops. Other examples of sequences are Strings, tuples, or sets.

Lists are similar in spirit to strings you can use the len() function and square brackets [ ] to access the data, with the first element indexed at 0.

Tip: if you'd like to know more, test, or practice your knowledge of Python lists, you can do so by going through the most common questions on Python lists here.

Now, on a practical note: you build up a list with two square brackets (start bracket and end bracket). Inside these brackets, you'll use commas to separate your values. You can then assign your list to a variable. The values that you put in a Python list can be of any data type, even lists!

Take a look at the following example of a list:

# Assign integer values to `a` and `b` a = 4 b = 9 # Create a list with the variables `a` and `b` count_list = [1,2,3,a,5,6,7,8,b,10] count_list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note that the values of a and b have been updated in the list count_list.

Creation of List

A list is created by placing all the items inside a square bracket [] separated by commas. It can have an infinite number of elements having various data types like string, integer, float, etc.

list1 = [1,2,3,4,5,6] #with same data type list1 [1, 2, 3, 4, 5, 6] list2 = [1, 'Aditya', 2.5] #with mixed data type list2 [1, 'Aditya', 2.5]

Accessing Elements from a List

Elements from the list can be accessed in various ways:

  • Index based: You can use the index operator to access the element from a list. In python, the indexing starts from 0 and ends at n-1, where n is the number of elements in the list.

    Indexing can be further categorized into positive and negative indexing.

index = [1,2,3,4,5] index[0], index[4] #positive indexing (1, 5) index[5] #this will give an error since there is no element at index 5 in the list --------------------------------------------------------------------------- IndexError Traceback (most recent call last) in ----> 1 index[5] #this will give an error since there is no element at index 5 in the list IndexError: list index out of range index[-1], index[-2] #negative indexing, here -1 means select first element from the last (5, 4)
  • Slice based: This is helpful when you want to access a sequence/range of elements from the list. The semicolon (:) is used as a slice operator to access the elements.
index[:3], index[2:] ([1, 2, 3], [3, 4, 5])

List Methods

Some of the most commonly used list methods are :

How do you use list comprehension?

Python - List Comprehension

List comprehension in Python is an easy and compact syntax for creating a list from a string or another list. It is a very concise way to create a new list by performing an operation on each item in the existing list. List comprehension is considerably faster than processing a list using the for loop.

List Comprehension Syntax:

[expression for element in iterable if condition]

As per the above syntax, the list comprehension syntax contains three parts: an expression, one or more for loop, and optionally, one or more if conditions. The list comprehension must be in the square brackets []. The result of the first expression will be stored in the new list. The for loop is used to iterate over the iterable object that optionally includes the if condition.

Suppose we want to find even numbers from 0 to 20 then we can do it using a for loop, as shown below:

Example: Create List of Even Numbers without List Comprehension

Copy

even_nums = [] for x in range(21): if x%2 == 0: even_nums.append(x) print(even_nums)

Output

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

The same result can be easily achieved using a list comprehension technique shown below.

Example: Create List of Even Numbers with List Comprehension

Copy

even_nums = [x for x in range(21) if x%2 == 0] print(even_nums)

Output

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

In the above example, [x for x in range(21) if x%2 == 0] returns a new list using the list comprehension. First, it executes the for loop for x in range(21) if x%2 == 0. The element x would be returned if the specified condition if x%2 == 0 evaluates to True. If the condition evaluates to True, then the expression before for loop would be executed and stored in the new list. Here, expression x simply stores the value of x into a new list.

List comprehension works with string lists also. The following creates a new list of strings that contains 'a'.

Example: List Comprehension with String List

Copy

names = ['Steve', 'Bill', 'Ram', 'Mohan', 'Abdul'] names2 = [s for s in names if 'a' in s] print(names2)

Output

['Ram', 'Mohan']

Above, the expression if 'a' in s returns True if an element contains a character 'a'. So, the new list will include names that contain 'a'.

The following example uses a list comprehension to build a list of squares of the numbers between 1 and 10.

Example: List Comprehension

Copy

squares = [x*x for x in range(11)] print(squares)

Output

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Above, a for loop for x in range(11) is executed without any if condition. The expression before for loop x*x stores the square of the element in the new list.

What is List Comprehension in Python?

So, let’s start with the syntax of list comprehension. List comprehension is a single line of code that you write inside the square brackets. It has three components:

  1. For loop
  2. Condition and expression
  3. Output
How do you use list comprehension?
Syntax of list comprehension -Credit buggyprogrammer

Example of Simple List Comprehension

The below code snippet is an example of the simplest list comprehension. Here we are just looping through the lst and storing all its element in the list a:

lst = [1,2,3,4,5,6,7,8,9,10] # simple list comprehension a = [x for x in lst] print(a) # ouput [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The above code is equivalent to this:

for x in lst: a.append(x)

In order to achieve this, we don’t even need the append method in a list comprehension.

Now in the above code (list comprehension), you can use any expression to modify the elements of lst, for example:

# add any number to every elements of lst and store it in a a = [x+1 for x in lst] # subtract any number to every elements of lst and store it in a a = [x-1 for x in lst] # multiply any number to every elements of lst and store it in a a = [x*2 for x in lst]

What are list comprehensions?

List comprehensions are a tool for transforming one list (any iterable actually) into another list. During this transformation, elements can be conditionally included in the new list and each element can be transformed as needed.

If you’re familiar with functional programming, you can think of list comprehensions as syntactic sugar for a filter followed by a map:

1 2 >>> doubled_odds = map(lambda n: n * 2, filter(lambda n: n % 2 == 1, numbers)) >>> doubled_odds = [n * 2 for n in numbers if n % 2 == 1]

If you’re not familiar with functional programming, don’t worry: I’ll explain using for loops.