1

The given code flattens the vector but I'd like to understand the execution order of the two for loops. I've checked the Python Docs too but the execution pattern is not given.

>>> # flatten a list using a list comprehension with two 'for'
>>> 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]

As I understand, execution order is like abstraction (left to right)? Is there any other opinion about it.

This link is flatten using lambda expression, and my question is regarding validation of two for loop execution in List Comp: How to make a flat list out of list of lists?

2 Answers2

2

It works left to right and is the short form of:

vec = [[1,2,3], [4,5,6], [7,8,9]]
flatten = []
for elem in vec:
    for num in elem:
        flatten.append(num)

This will give you the same output as [num for elem in vec for num in elem].

[1, 2, 3, 4, 5, 6, 7, 8, 9]
1

You are right about it being left to right. It's true when you look at the equivalent too (because of indentation):

vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
output = []
for elem in vec:     # first layer
    for num in elem: # second layer
        output.append(num)
GeeTransit
  • 1,458
  • 9
  • 22