I wanted to loop over a list an split every three items into one final list i came up with followings :
list comprehension :
inputs = ["1, foo, bar", "2, tom, jerry"] mylist= [[int(x), y.strip(), z.strip()] for s in inputs for x, y, z in [s.split(",")]]
and for loop :
inputs = ["1, foo, bar", "2, tom, jerry"] final= for input in inputs: x,y,z=input.split(',') final.append([int(x),y.strip(),z.strip()])
but in list comprehension method it was not unpacking into those three variables until i placed
[s.split(",")] within bracket while in for loop method it is not needed .
Im curious to know why additional bracket is needed in list comprehension while it is not needed in for loop method ?
The difference is that
x,y,z = input.split(',') is an assignment whereas
for x, y, z in [s.split(",")] iterates over a collection, just as it would do in regular nested loops. Without the
[...] it tries to iterate over the collection returned by
s.split and fails to unpack those strings into three variables.
This singleton list approach is actually a common way to create temporary variables in a list comprehension, although I’d suggest to
split(", ") so you don’t have to
mylist= [[int(x), y, z] for s in inputs for x, y, z in [s.split(", ")]]
Alternatively, use a nested generator expression in the list comprehension:
mylist= [[int(x), y, z] for x, y, z in (s.split(", ") for s in inputs)]
The latter is probably the preferred variant, but may not be feasible in all situations.