How can I do assignments in a list comprehension?

xunzhang picture xunzhang · Apr 24, 2012 · Viewed 54k times · Source

I want to use the assignment operator in a list comprehension. How can I do that?

The following code is invalid syntax. I mean to set lst[0] to an empty string '' if it matches pattern:

[ lst[0] = '' for pattern in start_pattern if lst[0] == pattern ]

Thanks!

Answer

n1k31t4 picture n1k31t4 · Feb 4, 2019

Python 3.8 will introduce Assignment Expressions.

It is a new symbol: := that allows assignment in (among other things) comprehensions. This new operator is also known as the walrus operator.

It will introduce a lot of potential savings w.r.t. computation/memory, as can be seen from the following snippet of the above linked PEP (formatting adapted for SO):

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:

  1. Handle a matched regex

    if (match := pattern.search(data)) is not None:
        # Do something with match
    
  2. A loop that can't be trivially rewritten using 2-arg iter()

    while chunk := file.read(8192):
        process(chunk)
    
  3. Reuse a value that's expensive to compute

    [y := f(x), y**2, y**3]
    
  4. Share a subexpression between a comprehension filter clause and its output

    filtered_data = [y for x in data if (y := f(x)) is not None]
    

This is already available in the recently releases alpha version (not recommended for production systems!). You can find the release schedule for Python 3.8 here.