Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

split method in list comprehension and for loop difference

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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 strip afterwards:

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading