Search code examples
pythonwalrus-operator

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


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?


Solution

  • 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']]