I am trying to find out if there is a way to split the value of each iteration of a list comprehension only once but use it twice in the output.
As an example of th
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), it's possible to use a local variable within a list comprehension in order to avoid calling twice the same expression:
In our case, we can name the evaluation of line.split(';')
as a variable parts
while using the result of the expression to filter the list if parts[1]
is not equal to 5
; and thus re-use parts
to produce the mapped value:
# text = '1;2;4\n3;4;5'
[(parts[1], parts[2]) for line in text.split('\n') if (parts := line.split(';'))[1] != 5]
# [('2', '4'), ('4', '5')]