python-assignment-expression

Expression that returns mutated list

Expression that returns mutated list Question: I’m looking for a single expression, mutates an element and returns the modified list The following is a bit verbose # key=0; value=3; rng=[1,2] [(v if i != key else value) for i, v in enumerate(rng)] Edit: I’m looking for a way to inline the following function in a …

Total answers: 3

Walrus to unpack values within a list comprehension

Walrus to unpack values within a list comprehension Question: I have a nested list holding dictionaries as mapping table using a tuple as key. I am struggling to zip the dictionary together so it can be exported by Pandas to csv file: l = [{(‘A’, ‘B’): 1}, {(‘A’, ‘C’): 2}, {(‘A’, ‘D’): 3}] def dynDictCombiner(item): …

Total answers: 2

Why is it that I "cannot use assignment expressions with comparison" in Python?

Why is it that I "cannot use assignment expressions with comparison" in Python? Question: In the examples below x is assigned using the walrus operator and is then printed. mystring = "hello, world" #if 1 if x := mystring == "hello, world": print(x) #if 2 if x := (mystring == "hello, world"): print(x) #if 3 …

Total answers: 1

Python3.8 assignment expressions, use in list comprehension or as an expression

Python3.8 assignment expressions, use in list comprehension or as an expression Question: I recently discovered that assignment expressions exist. And I wanted to refactor some of my code to make use of them. Most of the places I wanted to use it were relatively straightforward to convert. However, I’m not sure of the syntax to …

Total answers: 2

With assignment expressions in Python 3.8, why do we need to use `as` in `with`?

With assignment expressions in Python 3.8, why do we need to use `as` in `with`? Question: Now that PEP 572 has been accepted, Python 3.8 is destined to have assignment expressions, so we can use an assignment expression in with, i.e. with (f := open(‘file.txt’)): for l in f: print(f) instead of with open(‘file.txt’) as …

Total answers: 1

Is it possible to add a where clause with list comprehension?

Is it possible to add a where clause with list comprehension? Question: Consider the following list comprehension [ (x,f(x)) for x in iterable if f(x) ] This filters the iterable based a condition f and returns the pairs of x,f(x). The problem with this approach is f(x) is calculated twice. It would be great if …

Total answers: 4