Python – trying to unpack a list comprehension to understand it

Question:

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.

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]

Asked By: user16242546

||

Answers:

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)

Answered By: Cobra
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.