Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers, Type Conversion and Mathematics

Python List

  • Python Tuple
  • Python Sets
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension

Python Lambda/Anonymous Function

  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python Dictionary Comprehension

Python Dictionary fromkeys()

  • Python range() Function
  • Python List insert()

Python List Comprehension

List comprehension offers a concise way to create a new list based on the values of an existing list.

Suppose we have a list of numbers and we desire to create a new list containing the double value of each element in the list.

Python List Comprehension

  • Syntax of List Comprehension

for every item in list , execute the expression if the condition is True .

Note: The if statement in list comprehension is optional.

  • for Loop vs. List Comprehension

List comprehension makes the code cleaner and more concise than for loop.

Let's write a program to print the square of each list element using both for loop and list comprehension.

List Comprehension

It's much easier to understand list comprehension once you know Python for loop() .

  • Conditionals in List Comprehension

List comprehensions can utilize conditional statements like if…else to filter existing lists.

Let's see an example of an if statement with list comprehension.

Here, list comprehension checks if the number from range(1, 10) is even or odd. If even, it appends the number in the list.

Note : The range() function generates a sequence of numbers. To learn more, visit Python range() .

Let's use if...else with list comprehension to find even and odd numbers.

Here, if an item in the numbers list is divisible by 2 , it appends Even to the list even_odd_list . Else, it appends Odd .

Let's use nested if with list comprehension to find even numbers that are divisible by 5 .

Here, list comprehension checks two conditions:

  • if y is divisible by 2 or not.
  • if yes, is y divisible by 5 or not.

If y satisfies both conditions, the number appends to num_list .

  • Example: List Comprehension with String

We can also use list comprehension with iterables other than lists.

Here, we used list comprehension to find vowels in the string 'Python' .

More on Python List Comprehension

We can also use nested loops in list comprehension. Let's write code to compute a multiplication table.

Here is how the nested list comprehension works:

Nested Loop in List Comprehension

Let's see the equivalent code using nested for loop.

Equivalent Nested for Loop

Here, the nested for loop generates the same output as the nested list comprehension. We can see that the code with list comprehension is much cleaner and concise.

Along with list comprehensions, we also use lambda functions to work with lists.

While list comprehension is commonly used for filtering a list based on some conditions, lambda functions are commonly used with functions like map() and filter() .

They are used for complex operations or when an anonymous function is required.

Let's look at an example.

We can achieve the same result using list comprehension by:

If we compare the two codes, list comprehension is straightforward and simpler to read and understand.

So unless we need to perform complex operations, we can stick to list comprehension.

Visit Python Lambda/ Function to learn more about the use of lambda functions in Python.

Table of Contents

  • Introduction

Video: Python List, Set & Dictionary Comprehension

Sorry about that.

Related Tutorials

Python Tutorial

Python Library

Cookie Policy

We use cookies to operate this website, improve usability, personalize your experience, and improve our marketing. Privacy Policy .

By clicking "Accept" or further use of this website, you agree to allow cookies.

  • Data Science
  • Data Analytics
  • Machine Learning

alfie-grace-headshot-square2.jpg

Python List Comprehension: single, multiple, nested, & more

The general syntax for list comprehension in Python is:

Quick Example

We've got a list of numbers called num_list , as follows:

Using list comprehension , we'd like to append any values greater than ten to a new list. We can do this as follows:

This solution essentially follows the same process as using a for loop to do the job, but using list comprehension can often be a neater and more efficient technique. The example below shows how we could create our new list using a for loop.

Using list comprehension instead of a for loop, we've managed to pack four lines of code into one clean statement.

In this article, we'll first look at the different ways to use list comprehensions to generate new lists. Then we'll see what the benefits of using list comprehensions are. Finally, we'll see how we can tackle multiple list comprehensions .

How list comprehension works

A list comprehension works by translating values from one list into another by placing a for statement inside a pair of brackets, formally called a generator expression .

A generator is an iterable object, which yields a range of values. Let's consider the following example, where for num in num_list is our generator and num is the yield.

In this case, Python has iterated through each item in num_list , temporarily storing the values inside of the num variable. We haven't added any conditions to the list comprehension, so all values are stored in the new list.

Conditional statements in list comprehensions

Let's try adding in an if statement so that the comprehension only adds numbers greater than four:

The image below represents the process followed in the above list comprehension:

python list comprehension without assignment

We could even add in another condition to omit numbers smaller than eight. Here, we can use and inside of a list comprehension:

But we could also write this without and as:

When using conditionals, Python checks whether our if statement returns True or False for each yield. When the if statement returns True , the yield is appended to the new list.

Adding functionality to list comprehensions

List comprehensions aren't just limited to filtering out unwanted list values, but we can also use them to apply functionality to the appended values. For example, let's say we'd like to create a list that contains squared values from the original list:

We can also combine any added functionality with comparison operators. We've got a lot of use out of num_list , so let's switch it up and start using a different list for our examples:

In the above example, our list comprehension has squared any values in alternative_list that fall between thirty and fifty. To help demonstrate what's happening above, see the diagram below:

python list comprehension without assignment

Using comparison operators

List comprehension also works with or , in and not .

Like in the example above using and , we can also use or :

Using in , we can check other lists as well:

Likewise, not in is also possible:

Lastly, we can use if statements before generator expressions within a list comprehension. By doing this, we can tell Python how to treat different values:

The example above stores values in our new list if they are greater than forty; this is covered by num if num > 40 . Python stores zero in their place for values that aren't greater than forty, as instructed by else 0 . See the image below for a visual representation of what's happening:

python list comprehension without assignment

Multiple List Comprehension

Naturally, you may want to use a list comprehension with two lists at the same time. The following examples demonstrate different use cases for multiple list comprehension.

Flattening lists

The following synax is the most common version of multiple list comprehension, which we'll use to flatten a list of lists:

The order of the loops in this style of list comprehension is somewhat counter-intuitive and difficult to remember, so be prepared to look it up again in the future! Regardless, the syntax for flattening lists is helpful for other problems that would require checking two lists for values.

Nested lists

We can use multiple list comprehension when nested lists are involved. Let's say we've got a list of lists populated with string-type values. If we'd like to convert these values from string-type to integer-type, we could do this using multiple list comprehensions as follows:

Readability

The problem with using multiple list comprehensions is that they can be hard to read, making life more difficult for other developers and yourself in the future. To demonstrate this, here's how the first solution looks when combining a list comprehension with a for loop:

Our hybrid solution isn't as sleek to look at, but it's also easier to pick apart and figure out what's happening behind the scenes. There's no limit on how deep multiple list comprehensions can go. If list_of_lists had more lists nested within its nested lists, we could do our integer conversion as follows:

As the example shows, our multiple list comprehensions have now become very difficult to read. It's generally agreed that multiple list comprehensions shouldn't go any deeper than two levels ; otherwise, it could heavily sacrifice readability. To prove the point, here's how we could use for loops instead to solve the problem above:

Speed Test: List Comprehension vs. for loop

When working with lists in Python, you'll likely often find yourself in situations where you'll need to translate values from one list to another based on specific criteria.

Generally, if you're working with small datasets, then using for loops instead of list comprehensions isn't the end of the world. However, as the sizes of your datasets start to increase, you'll notice that working through lists one item at a time can take a long time.

Let's generate a list of ten thousand random numbers, ranging in value from one to a million, and store this as num_list . We can then use a for loop and a list comprehension to generate a new list containing the num_list values greater than half a million. Finally, using %timeit , we can compare the speed of the two approaches:

The list comprehension solution runs twice as fast, so not only does it use less code, but it's also much quicker. With that in mind, it's also worth noting that for loops can be much more readable in certain situations, such as when using multiple list comprehensions.

Ultimately, if you're in a position where multiple list comprehensions are required, it's up to you if you'd prefer to prioritize performance over readability.

List comprehensions are an excellent tool for generating new lists based on your requirements. They're much faster than using a for loop and have the added benefit of making your code look neat and professional.

For situations where you're working with nested lists, multiple list comprehensions are also available to you. The concept of using comprehensions may seem a little complex at first, but once you've wrapped your head around them, you'll never look back!

Get updates in your inbox

Join over 7,500 data science learners.

Recent articles:

The 6 best python courses for 2024 – ranked by software engineer, best course deals for black friday and cyber monday 2024, sigmoid function, dot product, meet the authors.

alfie-grace-headshot-square2.jpg

Alfie graduated with a Master's degree in Mechanical Engineering from University College London. He's currently working as Data Scientist at Square Enix. Find him on  LinkedIn .

Brendan Martin

Back to blog index

Python Land

Python List Comprehension: Tutorial With Examples

There’s a concept called set-builder notation in mathematics, also called set comprehension. Inspired by this principle, Python offers list comprehensions. In fact, Python list comprehensions are one of the defining features of the language. It allows us to create concise, readable code that outperforms the uglier alternatives like for loops or using map() .

We’ll first look at the most well-known type: list comprehensions. Once we’ve got a good grasp of how they work, you’ll also learn about set comprehensions and dictionary comprehensions.

Table of Contents

  • 1 What are list comprehensions?
  • 2 Examples of list comprehensions
  • 3 More advanced examples
  • 4 Other comprehensions

What are list comprehensions?

A Python list comprehension is a language construct. It’s used to create a Python list based on an existing list. Sounds a little vague, but after a few examples, that ‘ah-ha!’ moment will follow, trust me.

The basic syntax of a list comprehension is:

The ‘if’-part is optional, as you’ll discover soon. However, we do need a list to start from. Or, more specifically, anything that can be iterated . We’ll use Python’s range() function, which is a special type of iterator called a generator: it generates a new number on each iteration.

Examples of list comprehensions

Enough theory, let’s look at the most basic example, and I encourage you to fire up a Python REPL to try this yourself:

Some observations:

  • The expression part is just x
  • Instead of a list, we use the range() function. We can use [1, 2, 3, 4] too, but using range() is more efficient and requires less typing for longer ranges.

The result is a list of elements, obtained from range() . Not very useful, but we did create our first Python list comprehension. We could just as well use:

So let’s throw in that if-statement to make it more useful:

The if -part acts like a filter. If the condition after the if resolves to True, the item is included. If it resolves to False, it’s omitted. This way, we can get only the even numbers using a list comprehension.

So far, our expression (the x ) has been really simple. Just to make this absolutely clear though, expression can be anything that is valid Python code and is considered an expression. Example:

This expression adds four to x, which is still quite simple. But we could also have done something more complicated, like calling a function with x as the argument:

More advanced examples

You mastered the basics; congrats! Let’s continue with some more advanced examples.

Nested list comprehension

If expression can be any valid Python expression, it can also be another list comprehension. This can be useful when you want to create a matrix:

Or, if you want to flatten the previous matrix:

The same, but with some more whitespace to make this clearer:

The first part loops over the matrix m . The second part loops over the elements in each vector.

Alternatives to list comprehensions

The Python language could do without comprehensions; it would just not look as beautiful. Using functional programming functions like map() and reduce() can do everything a list comprehension can.

Another alternative is using for-loops . If you’re coming from a C-style language, like Java, you’ll be tempted to use for loops. Although it’s not the end of the world, you should know that list comprehensions are more performant and considered a better coding style.

Other comprehensions

If there are list comprehensions, why not create dictionary comprehension as well? Or what about set comprehensions? As you might expect, both exist.

Set comprehensions

The syntax for a Python set comprehension is not much different. We just use curly braces instead of square brackets:

For example:

Dictionary comprehensions

A dictionary requires a key and a value. Otherwise, it’s the same trick again:

The only difference is that we define both the key and value in the expression part.

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Course for Beginners

Related articles

  • JSON in Python: How To Read, Write, and Parse
  • Python List: How To Create, Sort, Append, Remove, And More
  • Python Set: The Why And How With Example Code
  • Python YAML: How to Load, Read, and Write YAML

Leave a Comment Cancel reply

You must be logged in to post a comment.

Python Simplified

PythonSimplifiedcomLogo

Comprehensive Guide to Python List Comprehensions

  • June 28, 2021
  • Author - Chetan Ambi
  • Category - Python

Python List Comprehensions

Table of Contents

Introduction

Python list comprehensions provide a concise way of creating lists. For example, if you want to write code that squares all the numbers from 1 to 10, you would write as below (the traditional way). First, you need to create an empty list, then loop through all the elements, square each element and then append to the list. 

You can achieve the same result using Python list comprehensions as shown below. As you can see, list comprehensions are readable, concise, and more Pythonic.

Understanding list comprehensions don’t stop here. But there is much to learn about list comprehensions. In this comprehensive guide, we’ll dig deeper and understand more about the list comprehensions. Once you go through this guide, you would have mastered list comprehensions in Python. I know you are excited!! Let’s get started.

Lists are one of the sequence types in Python. Refer to our in-depth article  here   for introduction to sequence types in Python.

List Comprehensions

As mentioned earlier, list comprehensions are concise ways of creating lists. The general syntax of list comprehension looks as below. It consists of three parts: iteration, transformation, and filtering .

list-comprehension-syntax

  • Iteration: This is the first part that gets executed in a list comprehension that iterates through all the elements in the iterable. 
  • Transformation : As the name says transformation will be applied to each element in the iterable. In the above example, we are squaring each element from the iterable.
  • Filter (optional) : This is optional and it filters out some of the elements based on the conditions. The above example loops through all the elements from 1 to 10, filters out odd numbers and considers only positive numbers before applying the transformation.

Let’s see couple more examples of list comprehensions. The below example converts all the strings in the list to upper case.

Here is another example that displays all the numbers less than 50 that are even and divisible by 7.

What happens under the hood

Now that you have understood the syntax and how to write list comprehensions, let’s try to understand what goes on under the hood.

Whenever Python encounters a list comprehension, it creates a temporary function that gets executed during the runtime. The result is stored at some memory location and then gets assigned the variable on the LHS. Refer to the diagram below.

list-comprehension-as-a-function

You can confirm this by running the list comprehension through the dis module. In the below example, the built-in compile() function generates the bytecode of the list comprehension. Then when you run it through the dis module, it generates byte code instructions as below.

Refer to the output of dis below. The bytecode instruction has MAKE_FUNCTION , CALL_FUNCTION . This confirms that Python converts list comprehensions to temporary functions internally.

Since list comprehensions are internally treated as functions, they exhibit some of the properties of functions. List comprehensions also have local and global scopes . In the below example, num is a local variable and factor is a global variable. But you can still access the global variable factor inside the list comprehension.

Nested list comprehensions

It’s possible to write nested list comprehensions meaning you can include a list comprehension within another. One of the uses of nested list comprehensions is that they can be used to create n-dimensional matrices. 

In the example below, we are able to create a 5×5 matrix using nested list comprehensions.

Nested loops in list comprehensions

It’s also possible to include multiple loops in list comprehensions. You can use as many loops as you want. But, as a best practice, you should limit the depth to two so as not to lose the readability. The below example uses two for loops. 

One of the uses of nested loops is to vectorize the matrix (flattening the matrix). In the below example, my_matrix is a 2×2 matrix. Using nested loops, we are able to create a vectorized version.

Multi-line list comprehensions

Most of the examples you have seen are one-line list comprehensions. But note that you can also write multi-line list comprehensions and are preferred when you can’t fit all the instructions in one line. They just increase the readability and won’t offer any added benefit. See an example below.

The same multi-line list comprehension is written in the single line as below. As you can see this is not readable.

List comprehensions with conditionals (if-else)

You can also use if-else conditions with list comprehensions. An example of using the if condition was covered in the syntax section. However, let me provide two examples here one with if and another with if-else .

Using if conditional:

The below example uses the if statement to filter out the languages that start with the letter “P”. Notice that if statement comes after the loop. In general, if condition is used to filtering.

Using if-else conditional:

When the if-else is used with list comprehension, the syntax is a little different compared to comprehension with only if statement. The below example calculates the square even numbers and cube of odd numbers between 1 to 10 using an if-else statement.

Do you want to master Python for else and while else? Please read our detailed article here .

List comprehensions with walrus operator

You can create list comprehensions using the walrus operator := and is also called as “assignment expression”. The walrus operator was first introduced in Python 3.8. As mentioned in PEP 572, it was introduced to speedup the coding by writing short code.

The below example creates a list of even numbers between 0 to 10 using the walrus operator.

List comprehensions Vs map and filter

The map and filter function can also be used as alternatives to list comprehensions as both the functions help us in creating the list object. 

map vs. list comprehension

The below example shows that the list comprehension function can be an alternative to the map function. 

The below code also confirms that list comprehensions are faster than the map function.

filter vs. list comprehension

From the below example, it is evident that list comprehensions can be an alternative to the filter function. 

Even in this case, list comprehensions are faster than filter functions. Refer to the below example.

Set Comprehensions

You can also create set comprehensions but the only difference is they are enclosed within curly brackets { } . The below example creates set comprehension from a list. It converts all the strings in the given list to upper case and creates a set (of course, by removing the duplicates)

Dictionary Comprehensions

Dictionary comprehensions are also enclosed with { } brackets but its contents follow key: value format as you expect. The below example creates a dictionary comprehension from a list. It creates a dictionary with string as key and length of the string as value. 

Generator Expressions

The generator expressions look very similar to list comprehension with the difference is that generator expressions are enclosed within parenthesis ( ) . You could say generator comprehension a lazy version of list comprehension . 

In the below example, we created a list of squares of numbers between 1 to 10 that are even-numbered using generator expression. Note that the output of generator expression is a generator object. To get the result, you need to pass the generator object to the list constructor (or to a tuple or set the constructor based on your need). 

Generator Expressions Vs. List Comprehensions

a) Storage efficiency: A list comprehension stores the entire list in the memory whereas a generator yields one item at a time on-demand. Hence, generator expressions are more memory efficient than lists. As seen from the below example, the same code generator expression takes far less memory.

b) Speed efficiency: List comprehensions are faster than generator expressions. The same code takes 7 seconds for list comprehensions but 9 seconds with generator expressions.

c) Use list comprehensions if you need to iterate over the list multiple times. If not, consider using generator expressions. Because you won’t be able to iterate generator expression again once you already iterated over. See the example below. When you iterate over a second time, it returns an empty list. 

So, which one should you consider? list comprehensions or generator expressions. There is always a trade-off between memory and speed efficiency so you need to choose based on the requirements. 

Do we have tuple comprehensions?

No, there are no tuple comprehensions! As we have gone through earlier, list comprehensions loop through each item in the iterable and append to the list under the hood. You are mutating the list by appending elements to it. List, set and dictionary comprehensions exist because they are mutable. But tuple is an immutable object. Hence, we don’t have tuple comprehensions. 

Refer to this detailed discussion on the same subject on Stack Overflow.

  • List comprehensions provide a concise way of creating lists.
  • Apart from list comprehensions , Python also has set comprehensions , dictionary comprehensions , and generator expressions .
  • Under the hood, list comprehensions converted to equivalent functions.
  • List comprehensions come in different formats  — nested list comprehensions, with nested loop, with multi-lines, with walrus operator, with if and if-else conditionals, etc.
  • List comprehensions with if conditional is used for filtering while if-else is used when you want to perform different transformations based on the conditions.
  • List comprehensions can be a replacement for map, filter, reduce, and for loop . In most cases list comprehensions is faster than all these methods.
  • If you need to use more than two for loops in the comprehension then it’s better to use the traditional way of creating a list. Because using more than two for loops is not easy to readable.
  • Consider using generator expressions instead of list comprehension if you are dealing with large data and not iterating over the list multiple times.
  • Comprehensions are supposed to be concise , clear , and Pythonic . Don’t write complicated lengthy comprehensions that will defeat the very purpose of using them. 

[1]. https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

Chetan Ambi

Chetan Ambi

How to Use Python List Comprehensions (And When Not to Use Them)

Here's everything you need to know about using this amazing feature of Python that'll boost your productivity and code readability overnight.

You may have heard of Python's list comprehension. Maybe it's even something you've used without really understanding. Now is the time to learn, as we cover everything you need to know about list comprehension in Python.

Before getting started, it's worth refreshing yourself on how arrays and lists work in Python and how to use Python dictionaries .

What Is Python List Comprehension?

List comprehension sounds complex but it really isn't. In Python, it's simply a quick way to filter or refine a list based on some criteria.

It saves you having to write several lines of code (especially if you're in a loop already), and it keeps the readability of your code neat.

Be careful, however, as list comprehension is not always the answer. It's easy to get carried away and write complex comprehensions that are tough to read. Sometimes writing more code is better, especially if it helps readability. Stick to simple tasks, and keep code to a single responsibility.

How to Use List Comprehensions in Python

Note: These examples all use Python 3.6. If you're not sure of the differences between Python 3 and Python 2, then make sure you read our Python FAQ , where we cover this question and more.

Consider this bit of code that copies an array and turns each letter in that array into an uppercase. It does so by looping through each item in the array:

Now here's the same exact logic, except done in a single line of code using a basic Python list comprehension:

As you can see, the result is exactly the same, but the process involves significantly more code without list comprehension.

Let's break this simple example down.

This example creates a list called letters . This stores the lowercase letters "a", "b", "c", and "d". Supposing you want all these list elements to be uppercase? Well, without list comprehension, you have to create a new list to store the result (called upper_letters ), loop over every element in the letters list, convert each letter (and store it in result ---optional but good practice), and then append the uppercase letter to the new list. What a lot of work!

The list comprehension here is almost exactly equivalent to the loop alternative. It effectively says "for every letter in the letters list, convert them to uppercase, and return the result as a new list."

List comprehension can only work on lists, and must return a new list. Let's dig deeper.

There are three parts to a list comprehension (we'll cover the third part below). List comprehensions must start and end with square brackets ( [ and ] ). This is how it was designed, and lets Python know that you'll be working with a list.

Inside the square brackets, you need to start with the result. This is what you want to do with each list element.

In the example above, the following code converts each element (referenced by the variable name x ) to upper case by using the upper() method, which is part of the Python core library:

Next, you need to tell Python which list to work on, and assign each individual element to a variable. This is exactly the same as the for loop in the long winded example:

Every time the loop goes over the list, the value of x will change to whatever the current element is. It will start off as "a", and then "b", and so on.

If you put it all together (and assign it to a variable called upper_letters ), you'll be done:

Now, upper_letters will contain a list of uppercase letters, starting at "A", and then "B" and so on.

The Third Part of List Comprehension in Python

As we mentioned above, there's a third part to list comprehension.

Once you've done the two steps above, you can include an optional condition. This is like using an if statement to say "make me a new list, based on this old list, but only include elements which meet my criteria".

Here's what it looks like:

This example uses a new list called ages . The old_ages list is assembled using a list comprehension. The if condition on the end means that only list elements which meet the criteria are inserted into the new list. In this example, any ages greater than ten are allowed.

When Not to Use Python List Comprehensions

List comprehension is amazing once you've got the hang of it, but it's not useful in every circumstance. You probably shouldn't use it when you need more than one condition:

This code works, but it's starting to get long and confusing. Similarly, anything more than a simple function call may not work. In this example, you'll get an error:

This is perfectly valid code, but as you cannot uppercase a number, it won't work. This is one case when the longer loop is actually preferable, as you'll be able to do some exception handling:

Start Putting Python List Comprehensions to Use

Now that you know just how easy list comprehension is in Python, there's no reason not to be using it. Just remember to keep it simple, and consider the readability above all else.

Maybe you'll control an Arduino with Python , or what about a DIY Python network security camera ?

List Comprehension

Assignment to multiple variables, transforming elements, nested list comprehension.

List comprehensions are a highly interesting and useful Python feature that allow us to create and manipulate lists using a much shorter syntax.

The basic syntax of a list comprehension consists of square brackets [] enclosing an expression followed by a for clause. We can also include if clauses for filtering.

Let’s get into the details of these parts below.

The expression defines what to include in the new list for each item in the iterable. It can be a simple transformation or even a computation.

For instance, suppose we have a list of five numbers stored in numbers . We want to create another list from it and store the squares of these numbers in it. We can do this by declaring a list comprehension called squares that evaluates the square of each number through the expression.

We can use conditions to filter elements from the original iterable based on specified criteria.

Let’s filter a list containing numbers so that it only stores odd numbers. We can do this by adding an ‘if’ statement at the end of the list comprehension that only saves a number from the list if it is odd (i.e., num % 2 != 0).

Let’s take another example that only stores words if they are short (i.e., have a length of less than or equal to five).

List comprehensions can be used to assign values to multiple variables simultaneously. In the example below, we save both the number and its square as a pair in the pairs variables.

We can also call functions to transform elements during the creation of the new list.

Nested comprehensions allow us to process elements from nested iterables (i.e., a 2D array).

Let’s take a look at a more advanced example that takes the transpose of a matrix through two ‘for’ loops in a nested list comprehension.

Outer list comprehension (for i in range(len(my_matrix[0]))):

It iterates over the range of column indices in the original matrix.

For each column index i, it executes the inner list comprehension.

Inner list comprehension ([row[i] for row in my_matrix]):

For a specific column index i, it iterates over each row in the original matrix.

For each row, it extracts the element at the current column index i.

The result is a list containing all elements from the same column for the given index i.

The outer list comprehension as a whole creates a list of lists, where each inner list is the result of the inner comprehension for a specific column index. These inner lists collectively form the rows of the transposed matrix.

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python - list comprehension, list comprehension.

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

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:

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

Advertisement

The return value is a new list, leaving the old list unchanged.

The condition is like a filter that only accepts the items that valuate to True .

Only accept items that are not "apple":

The condition if x != "apple"  will return True for all elements other than "apple", making the new list contain all fruits except "apple".

The condition is optional and can be omitted:

With no if statement:

The iterable can be any iterable object, like a list, tuple, set etc.

You can use the range() function to create an iterable:

Same example, but with a condition:

Accept only numbers lower than 5:

The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list:

Set the values in the new list to upper case:

You can set the outcome to whatever you like:

Set all values in the new list to 'hello':

The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome:

Return "orange" instead of "banana":

The expression in the example above says:

"Return the item if it is not banana, if it is banana return orange".

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 572 – Assignment Expressions

The importance of real code, exceptional cases, scope of the target, relative precedence of :=, change to evaluation order, differences between assignment expressions and assignment statements, specification changes during implementation, _pydecimal.py, datetime.py, sysconfig.py, simplifying list comprehensions, capturing condition values, changing the scope rules for comprehensions, alternative spellings, special-casing conditional statements, special-casing comprehensions, lowering operator precedence, allowing commas to the right, always requiring parentheses, why not just turn existing assignment into an expression, with assignment expressions, why bother with assignment statements, why not use a sublocal scope and prevent namespace pollution, style guide recommendations, acknowledgements, a numeric example, appendix b: rough code translations for comprehensions, appendix c: no changes to scope semantics.

This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr .

As part of this change, there is also an update to dictionary comprehension evaluation order to ensure key expressions are executed before value expressions (allowing the key to be bound to a name and then re-used as part of calculating the corresponding value).

During discussion of this PEP, the operator became informally known as “the walrus operator”. The construct’s formal name is “Assignment Expressions” (as per the PEP title), but they may also be referred to as “Named Expressions” (e.g. the CPython reference implementation uses that name internally).

Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.

Additionally, naming sub-parts of a large expression can assist an interactive debugger, providing useful display hooks and partial results. Without a way to capture sub-expressions inline, this would require refactoring of the original code; with assignment expressions, this merely requires the insertion of a few name := markers. Removing the need to refactor reduces the likelihood that the code be inadvertently changed as part of debugging (a common cause of Heisenbugs), and is easier to dictate to another programmer.

During the development of this PEP many people (supporters and critics both) have had a tendency to focus on toy examples on the one hand, and on overly complex examples on the other.

The danger of toy examples is twofold: they are often too abstract to make anyone go “ooh, that’s compelling”, and they are easily refuted with “I would never write it that way anyway”.

The danger of overly complex examples is that they provide a convenient strawman for critics of the proposal to shoot down (“that’s obfuscated”).

Yet there is some use for both extremely simple and extremely complex examples: they are helpful to clarify the intended semantics. Therefore, there will be some of each below.

However, in order to be compelling , examples should be rooted in real code, i.e. code that was written without any thought of this PEP, as part of a useful application, however large or small. Tim Peters has been extremely helpful by going over his own personal code repository and picking examples of code he had written that (in his view) would have been clearer if rewritten with (sparing) use of assignment expressions. His conclusion: the current proposal would have allowed a modest but clear improvement in quite a few bits of code.

Another use of real code is to observe indirectly how much value programmers place on compactness. Guido van Rossum searched through a Dropbox code base and discovered some evidence that programmers value writing fewer lines over shorter lines.

Case in point: Guido found several examples where a programmer repeated a subexpression, slowing down the program, in order to save one line of code, e.g. instead of writing:

they would write:

Another example illustrates that programmers sometimes do more work to save an extra level of indentation:

This code tries to match pattern2 even if pattern1 has a match (in which case the match on pattern2 is never used). The more efficient rewrite would have been:

Syntax and semantics

In most contexts where arbitrary Python expressions can be used, a named expression can appear. This is of the form NAME := expr where expr is any valid Python expression other than an unparenthesized tuple, and NAME is an identifier.

The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value:

There are a few places where assignment expressions are not allowed, in order to avoid ambiguities or user confusion:

This rule is included to simplify the choice for the user between an assignment statement and an assignment expression – there is no syntactic position where both are valid.

Again, this rule is included to avoid two visually similar ways of saying the same thing.

This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

This rule is included to discourage side effects in a position whose exact semantics are already confusing to many users (cf. the common style recommendation against mutable default values), and also to echo the similar prohibition in calls (the previous bullet).

The reasoning here is similar to the two previous cases; this ungrouped assortment of symbols and operators composed of : and = is hard to read correctly.

This allows lambda to always bind less tightly than := ; having a name binding at the top level inside a lambda function is unlikely to be of value, as there is no way to make use of it. In cases where the name will be used more than once, the expression is likely to need parenthesizing anyway, so this prohibition will rarely affect code.

This shows that what looks like an assignment operator in an f-string is not always an assignment operator. The f-string parser uses : to indicate formatting options. To preserve backwards compatibility, assignment operator usage inside of f-strings must be parenthesized. As noted above, this usage of the assignment operator is not recommended.

An assignment expression does not introduce a new scope. In most cases the scope in which the target will be bound is self-explanatory: it is the current scope. If this scope contains a nonlocal or global declaration for the target, the assignment expression honors that. A lambda (being an explicit, if anonymous, function definition) counts as a scope for this purpose.

There is one special case: an assignment expression occurring in a list, set or dict comprehension or in a generator expression (below collectively referred to as “comprehensions”) binds the target in the containing scope, honoring a nonlocal or global declaration for the target in that scope, if one exists. For the purpose of this rule the containing scope of a nested comprehension is the scope that contains the outermost comprehension. A lambda counts as a containing scope.

The motivation for this special case is twofold. First, it allows us to conveniently capture a “witness” for an any() expression, or a counterexample for all() , for example:

Second, it allows a compact way of updating mutable state from a comprehension, for example:

However, an assignment expression target name cannot be the same as a for -target name appearing in any comprehension containing the assignment expression. The latter names are local to the comprehension in which they appear, so it would be contradictory for a contained use of the same name to refer to the scope containing the outermost comprehension instead.

For example, [i := i+1 for i in range(5)] is invalid: the for i part establishes that i is local to the comprehension, but the i := part insists that i is not local to the comprehension. The same reason makes these examples invalid too:

While it’s technically possible to assign consistent semantics to these cases, it’s difficult to determine whether those semantics actually make sense in the absence of real use cases. Accordingly, the reference implementation [1] will ensure that such cases raise SyntaxError , rather than executing with implementation defined behaviour.

This restriction applies even if the assignment expression is never executed:

For the comprehension body (the part before the first “for” keyword) and the filter expression (the part after “if” and before any nested “for”), this restriction applies solely to target names that are also used as iteration variables in the comprehension. Lambda expressions appearing in these positions introduce a new explicit function scope, and hence may use assignment expressions with no additional restrictions.

Due to design constraints in the reference implementation (the symbol table analyser cannot easily detect when names are re-used between the leftmost comprehension iterable expression and the rest of the comprehension), named expressions are disallowed entirely as part of comprehension iterable expressions (the part after each “in”, and before any subsequent “if” or “for” keyword):

A further exception applies when an assignment expression occurs in a comprehension whose containing scope is a class scope. If the rules above were to result in the target being assigned in that class’s scope, the assignment expression is expressly invalid. This case also raises SyntaxError :

(The reason for the latter exception is the implicit function scope created for comprehensions – there is currently no runtime mechanism for a function to refer to a variable in the containing class scope, and we do not want to add such a mechanism. If this issue ever gets resolved this special case may be removed from the specification of assignment expressions. Note that the problem already exists for using a variable defined in the class scope from a comprehension.)

See Appendix B for some examples of how the rules for targets in comprehensions translate to equivalent code.

The := operator groups more tightly than a comma in all syntactic positions where it is legal, but less tightly than all other operators, including or , and , not , and conditional expressions ( A if C else B ). As follows from section “Exceptional cases” above, it is never allowed at the same level as = . In case a different grouping is desired, parentheses should be used.

The := operator may be used directly in a positional function call argument; however it is invalid directly in a keyword argument.

Some examples to clarify what’s technically valid or invalid:

Most of the “valid” examples above are not recommended, since human readers of Python source code who are quickly glancing at some code may miss the distinction. But simple cases are not objectionable:

This PEP recommends always putting spaces around := , similar to PEP 8 ’s recommendation for = when used for assignment, whereas the latter disallows spaces around = used for keyword arguments.)

In order to have precisely defined semantics, the proposal requires evaluation order to be well-defined. This is technically not a new requirement, as function calls may already have side effects. Python already has a rule that subexpressions are generally evaluated from left to right. However, assignment expressions make these side effects more visible, and we propose a single change to the current evaluation order:

  • In a dict comprehension {X: Y for ...} , Y is currently evaluated before X . We propose to change this so that X is evaluated before Y . (In a dict display like {X: Y} this is already the case, and also in dict((X, Y) for ...) which should clearly be equivalent to the dict comprehension.)

Most importantly, since := is an expression, it can be used in contexts where statements are illegal, including lambda functions and comprehensions.

Conversely, assignment expressions don’t support the advanced features found in assignment statements:

  • Multiple targets are not directly supported: x = y = z = 0 # Equivalent: (z := (y := (x := 0)))
  • Single assignment targets other than a single NAME are not supported: # No equivalent a [ i ] = x self . rest = []
  • Priority around commas is different: x = 1 , 2 # Sets x to (1, 2) ( x := 1 , 2 ) # Sets x to 1
  • Iterable packing and unpacking (both regular or extended forms) are not supported: # Equivalent needs extra parentheses loc = x , y # Use (loc := (x, y)) info = name , phone , * rest # Use (info := (name, phone, *rest)) # No equivalent px , py , pz = position name , phone , email , * other_info = contact
  • Inline type annotations are not supported: # Closest equivalent is "p: Optional[int]" as a separate declaration p : Optional [ int ] = None
  • Augmented assignment is not supported: total += tax # Equivalent: (total := total + tax)

The following changes have been made based on implementation experience and additional review after the PEP was first accepted and before Python 3.8 was released:

  • for consistency with other similar exceptions, and to avoid locking in an exception name that is not necessarily going to improve clarity for end users, the originally proposed TargetScopeError subclass of SyntaxError was dropped in favour of just raising SyntaxError directly. [3]
  • due to a limitation in CPython’s symbol table analysis process, the reference implementation raises SyntaxError for all uses of named expressions inside comprehension iterable expressions, rather than only raising them when the named expression target conflicts with one of the iteration variables in the comprehension. This could be revisited given sufficiently compelling examples, but the extra complexity needed to implement the more selective restriction doesn’t seem worthwhile for purely hypothetical use cases.

Examples from the Python standard library

env_base is only used on these lines, putting its assignment on the if moves it as the “header” of the block.

  • Current: env_base = os . environ . get ( "PYTHONUSERBASE" , None ) if env_base : return env_base
  • Improved: if env_base := os . environ . get ( "PYTHONUSERBASE" , None ): return env_base

Avoid nested if and remove one indentation level.

  • Current: if self . _is_special : ans = self . _check_nans ( context = context ) if ans : return ans
  • Improved: if self . _is_special and ( ans := self . _check_nans ( context = context )): return ans

Code looks more regular and avoid multiple nested if. (See Appendix A for the origin of this example.)

  • Current: reductor = dispatch_table . get ( cls ) if reductor : rv = reductor ( x ) else : reductor = getattr ( x , "__reduce_ex__" , None ) if reductor : rv = reductor ( 4 ) else : reductor = getattr ( x , "__reduce__" , None ) if reductor : rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )
  • Improved: if reductor := dispatch_table . get ( cls ): rv = reductor ( x ) elif reductor := getattr ( x , "__reduce_ex__" , None ): rv = reductor ( 4 ) elif reductor := getattr ( x , "__reduce__" , None ): rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )

tz is only used for s += tz , moving its assignment inside the if helps to show its scope.

  • Current: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) tz = self . _tzstr () if tz : s += tz return s
  • Improved: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) if tz := self . _tzstr (): s += tz return s

Calling fp.readline() in the while condition and calling .match() on the if lines make the code more compact without making it harder to understand.

  • Current: while True : line = fp . readline () if not line : break m = define_rx . match ( line ) if m : n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v else : m = undef_rx . match ( line ) if m : vars [ m . group ( 1 )] = 0
  • Improved: while line := fp . readline (): if m := define_rx . match ( line ): n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v elif m := undef_rx . match ( line ): vars [ m . group ( 1 )] = 0

A list comprehension can map and filter efficiently by capturing the condition:

Similarly, a subexpression can be reused within the main expression, by giving it a name on first use:

Note that in both cases the variable y is bound in the containing scope (i.e. at the same level as results or stuff ).

Assignment expressions can be used to good effect in the header of an if or while statement:

Particularly with the while loop, this can remove the need to have an infinite loop, an assignment, and a condition. It also creates a smooth parallel between a loop which simply uses a function call as its condition, and one which uses that as its condition but also uses the actual value.

An example from the low-level UNIX world:

Rejected alternative proposals

Proposals broadly similar to this one have come up frequently on python-ideas. Below are a number of alternative syntaxes, some of them specific to comprehensions, which have been rejected in favour of the one given above.

A previous version of this PEP proposed subtle changes to the scope rules for comprehensions, to make them more usable in class scope and to unify the scope of the “outermost iterable” and the rest of the comprehension. However, this part of the proposal would have caused backwards incompatibilities, and has been withdrawn so the PEP can focus on assignment expressions.

Broadly the same semantics as the current proposal, but spelled differently.

Since EXPR as NAME already has meaning in import , except and with statements (with different semantics), this would create unnecessary confusion or require special-casing (e.g. to forbid assignment within the headers of these statements).

(Note that with EXPR as VAR does not simply assign the value of EXPR to VAR – it calls EXPR.__enter__() and assigns the result of that to VAR .)

Additional reasons to prefer := over this spelling include:

  • In if f(x) as y the assignment target doesn’t jump out at you – it just reads like if f x blah blah and it is too similar visually to if f(x) and y .
  • import foo as bar
  • except Exc as var
  • with ctxmgr() as var

To the contrary, the assignment expression does not belong to the if or while that starts the line, and we intentionally allow assignment expressions in other contexts as well.

  • NAME = EXPR
  • if NAME := EXPR

reinforces the visual recognition of assignment expressions.

This syntax is inspired by languages such as R and Haskell, and some programmable calculators. (Note that a left-facing arrow y <- f(x) is not possible in Python, as it would be interpreted as less-than and unary minus.) This syntax has a slight advantage over ‘as’ in that it does not conflict with with , except and import , but otherwise is equivalent. But it is entirely unrelated to Python’s other use of -> (function return type annotations), and compared to := (which dates back to Algol-58) it has a much weaker tradition.

This has the advantage that leaked usage can be readily detected, removing some forms of syntactic ambiguity. However, this would be the only place in Python where a variable’s scope is encoded into its name, making refactoring harder.

Execution order is inverted (the indented body is performed first, followed by the “header”). This requires a new keyword, unless an existing keyword is repurposed (most likely with: ). See PEP 3150 for prior discussion on this subject (with the proposed keyword being given: ).

This syntax has fewer conflicts than as does (conflicting only with the raise Exc from Exc notation), but is otherwise comparable to it. Instead of paralleling with expr as target: (which can be useful but can also be confusing), this has no parallels, but is evocative.

One of the most popular use-cases is if and while statements. Instead of a more general solution, this proposal enhances the syntax of these two statements to add a means of capturing the compared value:

This works beautifully if and ONLY if the desired condition is based on the truthiness of the captured value. It is thus effective for specific use-cases (regex matches, socket reads that return '' when done), and completely useless in more complicated cases (e.g. where the condition is f(x) < 0 and you want to capture the value of f(x) ). It also has no benefit to list comprehensions.

Advantages: No syntactic ambiguities. Disadvantages: Answers only a fraction of possible use-cases, even in if / while statements.

Another common use-case is comprehensions (list/set/dict, and genexps). As above, proposals have been made for comprehension-specific solutions.

This brings the subexpression to a location in between the ‘for’ loop and the expression. It introduces an additional language keyword, which creates conflicts. Of the three, where reads the most cleanly, but also has the greatest potential for conflict (e.g. SQLAlchemy and numpy have where methods, as does tkinter.dnd.Icon in the standard library).

As above, but reusing the with keyword. Doesn’t read too badly, and needs no additional language keyword. Is restricted to comprehensions, though, and cannot as easily be transformed into “longhand” for-loop syntax. Has the C problem that an equals sign in an expression can now create a name binding, rather than performing a comparison. Would raise the question of why “with NAME = EXPR:” cannot be used as a statement on its own.

As per option 2, but using as rather than an equals sign. Aligns syntactically with other uses of as for name binding, but a simple transformation to for-loop longhand would create drastically different semantics; the meaning of with inside a comprehension would be completely different from the meaning as a stand-alone statement, while retaining identical syntax.

Regardless of the spelling chosen, this introduces a stark difference between comprehensions and the equivalent unrolled long-hand form of the loop. It is no longer possible to unwrap the loop into statement form without reworking any name bindings. The only keyword that can be repurposed to this task is with , thus giving it sneakily different semantics in a comprehension than in a statement; alternatively, a new keyword is needed, with all the costs therein.

There are two logical precedences for the := operator. Either it should bind as loosely as possible, as does statement-assignment; or it should bind more tightly than comparison operators. Placing its precedence between the comparison and arithmetic operators (to be precise: just lower than bitwise OR) allows most uses inside while and if conditions to be spelled without parentheses, as it is most likely that you wish to capture the value of something, then perform a comparison on it:

Once find() returns -1, the loop terminates. If := binds as loosely as = does, this would capture the result of the comparison (generally either True or False ), which is less useful.

While this behaviour would be convenient in many situations, it is also harder to explain than “the := operator behaves just like the assignment statement”, and as such, the precedence for := has been made as close as possible to that of = (with the exception that it binds tighter than comma).

Some critics have claimed that the assignment expressions should allow unparenthesized tuples on the right, so that these two would be equivalent:

(With the current version of the proposal, the latter would be equivalent to ((point := x), y) .)

However, adopting this stance would logically lead to the conclusion that when used in a function call, assignment expressions also bind less tight than comma, so we’d have the following confusing equivalence:

The less confusing option is to make := bind more tightly than comma.

It’s been proposed to just always require parentheses around an assignment expression. This would resolve many ambiguities, and indeed parentheses will frequently be needed to extract the desired subexpression. But in the following cases the extra parentheses feel redundant:

Frequently Raised Objections

C and its derivatives define the = operator as an expression, rather than a statement as is Python’s way. This allows assignments in more contexts, including contexts where comparisons are more common. The syntactic similarity between if (x == y) and if (x = y) belies their drastically different semantics. Thus this proposal uses := to clarify the distinction.

The two forms have different flexibilities. The := operator can be used inside a larger expression; the = statement can be augmented to += and its friends, can be chained, and can assign to attributes and subscripts.

Previous revisions of this proposal involved sublocal scope (restricted to a single statement), preventing name leakage and namespace pollution. While a definite advantage in a number of situations, this increases complexity in many others, and the costs are not justified by the benefits. In the interests of language simplicity, the name bindings created here are exactly equivalent to any other name bindings, including that usage at class or module scope will create externally-visible names. This is no different from for loops or other constructs, and can be solved the same way: del the name once it is no longer needed, or prefix it with an underscore.

(The author wishes to thank Guido van Rossum and Christoph Groth for their suggestions to move the proposal in this direction. [2] )

As expression assignments can sometimes be used equivalently to statement assignments, the question of which should be preferred will arise. For the benefit of style guides such as PEP 8 , two recommendations are suggested.

  • If either assignment statements or assignment expressions can be used, prefer statements; they are a clear declaration of intent.
  • If using assignment expressions would lead to ambiguity about execution order, restructure it to use statements instead.

The authors wish to thank Alyssa Coghlan and Steven D’Aprano for their considerable contributions to this proposal, and members of the core-mentorship mailing list for assistance with implementation.

Appendix A: Tim Peters’s findings

Here’s a brief essay Tim Peters wrote on the topic.

I dislike “busy” lines of code, and also dislike putting conceptually unrelated logic on a single line. So, for example, instead of:

instead. So I suspected I’d find few places I’d want to use assignment expressions. I didn’t even consider them for lines already stretching halfway across the screen. In other cases, “unrelated” ruled:

is a vast improvement over the briefer:

The original two statements are doing entirely different conceptual things, and slamming them together is conceptually insane.

In other cases, combining related logic made it harder to understand, such as rewriting:

as the briefer:

The while test there is too subtle, crucially relying on strict left-to-right evaluation in a non-short-circuiting or method-chaining context. My brain isn’t wired that way.

But cases like that were rare. Name binding is very frequent, and “sparse is better than dense” does not mean “almost empty is better than sparse”. For example, I have many functions that return None or 0 to communicate “I have nothing useful to return in this case, but since that’s expected often I’m not going to annoy you with an exception”. This is essentially the same as regular expression search functions returning None when there is no match. So there was lots of code of the form:

I find that clearer, and certainly a bit less typing and pattern-matching reading, as:

It’s also nice to trade away a small amount of horizontal whitespace to get another _line_ of surrounding code on screen. I didn’t give much weight to this at first, but it was so very frequent it added up, and I soon enough became annoyed that I couldn’t actually run the briefer code. That surprised me!

There are other cases where assignment expressions really shine. Rather than pick another from my code, Kirill Balunov gave a lovely example from the standard library’s copy() function in copy.py :

The ever-increasing indentation is semantically misleading: the logic is conceptually flat, “the first test that succeeds wins”:

Using easy assignment expressions allows the visual structure of the code to emphasize the conceptual flatness of the logic; ever-increasing indentation obscured it.

A smaller example from my code delighted me, both allowing to put inherently related logic in a single line, and allowing to remove an annoying “artificial” indentation level:

That if is about as long as I want my lines to get, but remains easy to follow.

So, in all, in most lines binding a name, I wouldn’t use assignment expressions, but because that construct is so very frequent, that leaves many places I would. In most of the latter, I found a small win that adds up due to how often it occurs, and in the rest I found a moderate to major win. I’d certainly use it more often than ternary if , but significantly less often than augmented assignment.

I have another example that quite impressed me at the time.

Where all variables are positive integers, and a is at least as large as the n’th root of x, this algorithm returns the floor of the n’th root of x (and roughly doubling the number of accurate bits per iteration):

It’s not obvious why that works, but is no more obvious in the “loop and a half” form. It’s hard to prove correctness without building on the right insight (the “arithmetic mean - geometric mean inequality”), and knowing some non-trivial things about how nested floor functions behave. That is, the challenges are in the math, not really in the coding.

If you do know all that, then the assignment-expression form is easily read as “while the current guess is too large, get a smaller guess”, where the “too large?” test and the new guess share an expensive sub-expression.

To my eyes, the original form is harder to understand:

This appendix attempts to clarify (though not specify) the rules when a target occurs in a comprehension or in a generator expression. For a number of illustrative examples we show the original code, containing a comprehension, and the translation, where the comprehension has been replaced by an equivalent generator function plus some scaffolding.

Since [x for ...] is equivalent to list(x for ...) these examples all use list comprehensions without loss of generality. And since these examples are meant to clarify edge cases of the rules, they aren’t trying to look like real code.

Note: comprehensions are already implemented via synthesizing nested generator functions like those in this appendix. The new part is adding appropriate declarations to establish the intended scope of assignment expression targets (the same scope they resolve to as if the assignment were performed in the block containing the outermost comprehension). For type inference purposes, these illustrative expansions do not imply that assignment expression targets are always Optional (but they do indicate the target binding scope).

Let’s start with a reminder of what code is generated for a generator expression without assignment expression.

  • Original code (EXPR usually references VAR): def f (): a = [ EXPR for VAR in ITERABLE ]
  • Translation (let’s not worry about name conflicts): def f (): def genexpr ( iterator ): for VAR in iterator : yield EXPR a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a simple assignment expression.

  • Original code: def f (): a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): if False : TARGET = None # Dead code to ensure TARGET is a local variable def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a global TARGET declaration in f() .

  • Original code: def f (): global TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): global TARGET def genexpr ( iterator ): global TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Or instead let’s add a nonlocal TARGET declaration in f() .

  • Original code: def g (): TARGET = ... def f (): nonlocal TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def g (): TARGET = ... def f (): nonlocal TARGET def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Finally, let’s nest two comprehensions.

  • Original code: def f (): a = [[ TARGET := i for i in range ( 3 )] for j in range ( 2 )] # I.e., a = [[0, 1, 2], [0, 1, 2]] print ( TARGET ) # prints 2
  • Translation: def f (): if False : TARGET = None def outer_genexpr ( outer_iterator ): nonlocal TARGET def inner_generator ( inner_iterator ): nonlocal TARGET for i in inner_iterator : TARGET = i yield i for j in outer_iterator : yield list ( inner_generator ( range ( 3 ))) a = list ( outer_genexpr ( range ( 2 ))) print ( TARGET )

Because it has been a point of confusion, note that nothing about Python’s scoping semantics is changed. Function-local scopes continue to be resolved at compile time, and to have indefinite temporal extent at run time (“full closures”). Example:

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0572.rst

Last modified: 2023-10-11 12:05:51 GMT

  • EyeHunts.com
  • Interview Puzzle

Python list comprehension if without else | Example code

  • September 12, 2021 May 10, 2022

We can use list comprehension using if without else in Python.

Python Example list comprehension if without else

A simple example code compares 2 iterable and prints the items which appear in both iterable .

Python list comprehension if without else

Can an if statement in a list comprehension use an else?

Answer: Yes, an else clause can be used with an if in a list comprehension. The following code example shows the use of an else in a simple list comprehension. The if/else is placed in front of them for a component of the list comprehension.

Output : [‘No’, ‘No’, ‘Yes’, ‘No’]

Do comment if you have any doubts or suggestions on this Python List tutorial.

Note: IDE:  PyCharm  2021.3.3 (Community Edition) Windows 10 Python 3.10.1 All  Python Examples are in Python 3 , so Maybe its different from python 2 or upgraded versions.

Share this:

Leave a reply cancel reply.

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

Notify me of follow-up comments by email.

Notify me of new posts by email.

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries
  • Comprehensions in Python
  • Appending Item to Lists of list using List Comprehension | Python
  • Python List Comprehension and Slicing
  • Python | Concatenate two lists element-wise
  • How to Create a List of N-Lists in Python
  • Python Merge Two Lists Without Duplicates
  • Python | Convert two lists into a dictionary
  • Convert List of Tuples To Multiple Lists in Python
  • How To Combine Multiple Lists Into One List Python
  • Python | Merge two list of lists according to first element
  • Python | Split nested list into two lists
  • Python | Convert list of tuples to list of list
  • Python | Combining tuples in list of tuples
  • Python - Convert Lists to Nested Dictionary
  • Python | Difference between two lists
  • Python | Adding two list elements
  • Merge Two Lists in Python
  • Python | List Comprehension Quiz | Question 1
  • Python | List Comprehension Quiz | Question 17

Python List Comprehension With Two Lists

We are given two lists and our task is to show the implementation of list comprehension with those two lists. In this article, we will see how we can use list comprehension with two list in Python and perform various operations on them.

Below are some of the ways by which we can use list comprehension with multiple lists in Python :

Using Conditional Statement

Using nested loops, using custom function, using enumerate() function, basic list comprehension.

In this example, the code adds corresponding elements from two lists, `list_a` and `list_b`, using Python list comprehension with the `zip` function. The result is a new list containing the sums. When printed, it outputs `[6, 8, 10, 12]`.

In this example, code creates a new list, `result`, by adding corresponding elements from `list_a` and `list_b` using list comprehension with a condition. It filters out elements whose sum is not even. The printed result is a list containing only the even sums, which is `[6, 10]`.

In this example, below code uses nested loops as list comprehension to create a new list, `result`, by multiplying each element from `list_a` with every element from `list_b`. The output is a flattened list of all possible products, resulting in `[5, 6, 7, 8, 10, 12, 15, 18, 21, 24, 30, 32]`.

In this example, code defines a custom function, `custom_function(a, b)`, which calculates the sum of squares of its arguments. Then, it uses list comprehension to create a new list, `result`, by applying this custom function to corresponding elements from `list_a` and `list_b`.

In this example, below code utilizes list comprehension with ` enumerate ` to create a new list, `result`, where each element is the product of the index and the corresponding pair of elements from `list_a` and `list_b`. The output is `[0, 6, 14, 24]`, representing the index multiplied by the sum of each pair.

Please Login to comment...

Similar reads.

  • python-basics
  • python-list
  • Python Programs

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. List Comprehension in python with example

    python list comprehension without assignment

  2. List Comprehension in Python Explained for Beginners

    python list comprehension without assignment

  3. Python List Comprehension

    python list comprehension without assignment

  4. Python list comprehension + dictionary comprehension with examples

    python list comprehension without assignment

  5. Python List Comprehensions in 5-minutes

    python list comprehension without assignment

  6. Python

    python list comprehension without assignment

VIDEO

  1. List Comprehension In Python In Under A Minute! ✅⚡⏲️ #coding #programming #python #shorts

  2. List Comprehension #python #list

  3. List Comprehension in Python

  4. 04. Python List Comprehension. Part

  5. Learn Python List Comprehension

  6. List comprehension

COMMENTS

  1. python

    use filter() - if your function returns None, you will get an empty list. Just a plain for -loop. while the plain loop is the preferable way to do it. It is semantically correct in this case, all other ways, including list comprehension, abuse concepts for their side-effect. In Python 3.x, map() and filter() are generators and thus do nothing ...

  2. List comprehension without [ ] in Python

    If you give it one, it can start its work immediately. If you give it a genexp instead, it cannot start work until it builds-up a new list in memory by running the genexp to exhaustion: ~ $ python -m timeit '"".join(str(n) for n in xrange(1000))'. 1000 loops, best of 3: 335 usec per loop.

  3. When to Use a List Comprehension in Python

    Here, you instantiate an empty list, squares.Then, you use a for loop to iterate over range(10).Finally, you multiply each number by itself and append the result to the end of the list.. Work With map Objects. For an alternative approach that's based in functional programming, you can use map().You pass in a function and an iterable, and map() will create an object.

  4. Python List Comprehension (With Examples)

    # create a new list using list comprehension square_numbers = [num ** 2 for num in numbers] If we compare the two codes, list comprehension is straightforward and simpler to read and understand. So unless we need to perform complex operations, we can stick to list comprehension.

  5. Python List Comprehension: single, multiple, nested, & more

    We've got a list of numbers called num_list, as follows: num_list = [4, 11, 2, 19, 7, 6, 25, 12] Learn Data Science with. Using list comprehension, we'd like to append any values greater than ten to a new list. We can do this as follows: new_list = [num for num in num_list if num > 10] new_list. Learn Data Science with.

  6. Python List Comprehension: Tutorial With Examples

    A Python list comprehension is a language construct. It's used to create a Python list based on an existing list. Sounds a little vague, but after a few examples, that 'ah-ha!' moment will follow, trust me. The basic syntax of a list comprehension is: [ <expression> for item in list if <conditional> ]

  7. Comprehensive Guide to Python List Comprehensions

    The general syntax of list comprehension looks as below. It consists of three parts: iteration, transformation, and filtering. squares = [num**2 for num in range(1,11) if num%2==0] Iteration: This is the first part that gets executed in a list comprehension that iterates through all the elements in the iterable.

  8. How to Use Python List Comprehensions (And When Not to Use Them)

    How to Use List Comprehensions in Python Note: These examples all use Python 3.6. If you're not sure of the differences between Python 3 and Python 2, then make sure you read our Python FAQ, where we cover this question and more.. Consider this bit of code that copies an array and turns each letter in that array into an uppercase.

  9. Python List Comprehension Tutorial

    Yes, starting from Python 3.8, even though this operation is rarely used. For this purpose, you should use the walrus operator :=. For example, the following list comprehension creates 5 times a random integer between 1 and 10 inclusive (you have first to import random), checks if it is greater than 3 and if so, assigns it to the variable x, which then adds to the list being created: [x for ...

  10. Python List Comprehension

    Learn how Python list comprehension can create powerful functionality within a single line of code and create a new list based on the values of an iterable. ... Assignment to multiple variables. List comprehensions can be used to assign values to multiple variables simultaneously. In the example below, we save both the number and its square as ...

  11. Python

    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:

  12. Python

    Python List Comprehension Syntax. Syntax: newList = [ expression (element) for element in oldList if condition ] Parameter: expression: Represents the operation you want to execute on every item within the iterable. element: The term "variable" refers to each value taken from the iterable. iterable: specify the sequence of elements you want ...

  13. The Do's and Don'ts of Python List Comprehension

    1. Don't forget about the list () constructor. Some people may think that list comprehension is a cool and Pythonic feature to show off their Python skills, and they tend to use it even when there are better alternatives. One such case is the use of the list() constructor. Consider some trivial examples below.

  14. 5. Data Structures

    5. Data Structures ¶. This chapter describes some things you've learned about already in more detail, and adds some new things as well. 5.1. More on List s ¶. The list data type has some more methods. Here are all of the methods of list objects: list. append (x) Add an item to the end of the list.

  15. PEP 572

    There is one special case: an assignment expression occurring in a list, set or dict comprehension or in a generator expression (below collectively referred to as "comprehensions") binds the target in the containing scope, honoring a nonlocal or global declaration for the target in that scope, if one exists. For the purpose of this rule the ...

  16. Complex List Comprehensions Can Be Readable!

    Python comprehensions allow for powerful computations in loops — even nested ones. Photo by Önder Örtel on Unsplash. Python comprehensions — including list, dictionary and set comprehensions as well as generator expressions — constitute a powerful Python syntactic sugar. You can read about them in the following articles:

  17. Appending Item to Lists of list using List Comprehension

    Append an Item to Lists Within A List Comprehension in Python. Below are some of the ways by which we can append an item to lists within a list comprehension in Python: Using the 'Or' operator. Using a non-in-place operator like '+'. Using List Comprehension without the assignment operator. Using the Extend Method.

  18. Python list comprehension if without else

    Do comment if you have any doubts or suggestions on this Python List tutorial. Note: IDE: PyCharm 2021.3.3 (Community Edition) Windows 10. Python 3.10.1. All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

  19. python

    0. You can use list comprehension. [ 3 if x >= 0 and x < 204 else 1 if x >= 204 and x < 419 else 2 for x in range(0, 620)] answered Sep 13, 2020 at 7:35. Ikhwan Rizqy Nurzaman. 1. It's less readability but list comprehension is the fastest and most efficient way to create a list in python. - Ikhwan Rizqy Nurzaman. Sep 13, 2020 at 8:09.

  20. Python List Comprehension With Two Lists

    In this example, the code adds corresponding elements from two lists, `list_a` and `list_b`, using Python list comprehension with the `zip` function. The result is a new list containing the sums. When printed, it outputs ` [6, 8, 10, 12]`. Python3. list_a = [1, 2, 3, 4]

  21. python

    Allowing this form of assignment within comprehensions, such as list comprehensions, and lambda functions where traditional assignments are forbidden. This can also facilitate interactive debugging without the need for code refactoring. Recommended use-case examples a) Getting conditional values. for example (in Python 3):