Interpretation of nested loops


I am curious how it is that python ‘knows’ how to distinguish between dummy variables when using nested loops. For example, take the following code:

Here I have a list of sublist transactions that are made up of tuples. In this case, I am calling each data point in the tuple transaction list a datum. But what I don’t understand is how python understands how to go a layer deeper in parsing the data structure.

If someone could please explain, that would be fantastic! Thank you.

It’s inception!

list_of_pairs = [[1, 2], [3, 4], [5, 6], [7, 8]]
for pairs in list_of_pairs:  # is told to iterate through [[1, 2], [3, 4], [5, 6], [7, 8]]
  for number in pairs: #is told to iterate through [1, 2], then [3, 4] ect...
    print(number) #prints individual numbers
    #for quarks in number: 

the last 2 lines that are commented out iterate though a single data point. Python doesn’t support quantum programming so this errors :laughing:, but demonstrates that it stops once you reach something that cannot be iterated upon. list_of_pairs is a list of lists, so you can run 2 for loops. [[[1, 2], [3, 4]][[5, 6], [7, 8]]] This confusing list of lists of lists would support 3 for loops: first the whole list, then [[1, 2], [3, 4]] finally [1, 2] would be looking at individual numbers. Though if those numbers were strings, you could still iterate through the individual letters.

Be sure to write the append statements in separate loop bodies. The second one should be indented to match the outer loop.

1 Like

Great! Thank you both @bavarcarus and @mtf !