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

Python – trying to unpack a list comprehension to understand it

This is a basic question that I am trying to figure out but can’t seem to. I have a list comprehension that works as expected (for Advent of Code). For my reference I am trying to unpack it.

raw_data = """
30373
25512
65332
33549
35390
"""

forest = [[int(x) for x in row] for row in raw_data.split()]
print(forest)

which outputs:
[[3, 0, 3, 7, 3], [2, 5, 5, 1, 2], [6, 5, 3, 3, 2], [3, 3, 5, 4, 9], [3, 5, 3, 9, 0]]

So I am trying to unpack it to better understand it but it’s not working as I expect.

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

t = []
for row in raw_data.split():
    for x in row:
        t.append(int(x))

print(t)

which outputs:
[3, 0, 3, 7, 3, 2, 5, 5, 1, 2, 6, 5, 3, 3, 2, 3, 3, 5, 4, 9, 3, 5, 3, 9, 0]

>Solution :

I think this is what you’re looking for:

t = []
for row in raw_data.split():
    r = []
    for x in row:
        r.append(int(x))
    t.append(r)

print(t)

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