why can't I use walrus in a one-line for expression

383 Views Asked by At

I'm trying to use walrus in a for loop to create a list,

something like this:

data = [l := line.strip().somefunc() for line in iterable_obj if(l[0] == 'sth')]

but it returns an empty list can someone give me a hint on what I'm doing wrong here?

4

There are 4 best solutions below

0
isaactfa On BEST ANSWER

You just need to swap where you put the assignment expression (because the condition is evaluated first):

iterable_obj = ("a", "b", "sth")

data = [l  for line in iterable_obj if (l := line.strip().split())[0] == 'sth']

print(data) # [['sth']]
2
funnydman On

No need to use walrus here, just do:

iterable_obj = ['   Hello world sth', '   here', 'we',  'go']
data = [line.strip() for line in iterable_obj if ('sth' not in line)]
print(data)

Output:

['here', 'we', 'go']
0
John M. On

it seems you need to define the walrus operator in the if as it's calculated first:

[j for i in range(10) if (j := i) == 5]

note in your example, you must have defined l elsewhere in code, as if I get an name error if I try to use j in the if statement while defining it on the left.

0
Axeltherabbit On

[evaluatedafter for x in L if evaluatedfirst]

in multiple lines you are trying to do this:

if l[0] == "something": # <- 'l' was never defined
   l = line.strip().somefunc()