It happens to me quite often to have a piece of code that looks like this.
raw_data = [(s.split(\',\')[0], s.split(\',\')[1]) for s in all_lines if s.split(\',
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 NaN
; and thus re-use parts
to produce the mapped value:
# lines = ['1,2,3,4', '5,NaN,7,8']
[(parts[0], parts[1]) for line in lines if (parts := line.split(','))[1] != 'NaN']
# [('1', '2')]