I was wondering how a nested loop iterates. For example:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for lst in lists: #for loop that loops through the indeces of list (the subsists)
for numbers in lst: #for loop that loops through the indices of sub-lists (the numbers)
results.append(numbers)
return results
Does the first for loop iterate each time the second (nested) for loop iterates each index? (so to iterate every number in the sub-lists, the first for loop iterates index 0 and index 1 - the two sub-lists - and then the second nested loop comes in and iterates one of the indeces (depending on the current iteration), then the process repeats...
OR
Does the first for loop iterate once through each sub-list and then the second loop comes in and iterates until every index in the sub-lists is iterated?
In other words:
Version 1:
Version 2:
And when the numbers in the sub-lists are iterated, do they get their own indices (0,1,2,etc. for sub-list 0, index 0,1,2,etc. for sub-list 1) for their index count is continuous between the two sub-lists?
its easy to check it by yourself:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for i,lst in enumerate(lists): #for loop that loops through the indeces of list (the subsists)
print("i=",i)
for j,numbers in enumerate(lst): #for loop that loops through the indices of sub-lists (the numbers)
print("j=",j)
results.append(numbers)
return results
Which gives:
i= 0 #<-- first loop
j= 0 #<-- second loop
j= 1 #<-- second loop
j= 2 #<-- second loop
i= 1 #<-- first loop
j= 0 #<-- second loop
j= 1 #<-- second loop
j= 2 #<-- second loop
j= 3 #<-- second loop
j= 4 #<-- second loop
j= 5 #<-- second loop