-3

Whilst I know what this piece of code does i have no clue how it achieves it. Can someone please explain it in the dumbest way?

vec = [[1,2,3], [4,5,6], [7,8,9]]
[num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

The first for part of the code returns this:

[num for elem in vec]
[0, 0, 0]

Are they indexes for each nested lists first entry?

Thanks!

1 Answers1

0

It's just a list comprehension with two loops. It's roughly equal to this:

ls = [] 
for elem in vec:
    for num in elem:
        ls.append(num)

 

The first for part of the code returns this:

[num for elem in vec]
[0, 0, 0]

It doesn't make sense to only look at that part of the code. That's like only looking at the last 2 lines of my answer's code example and trying to understand what they're doing without looking at the other lines.

ruohola
  • 21,987
  • 6
  • 62
  • 97