I can not figure out why this result comes out, someone briefly explain:

rows = range(1, 4) cols = range(1, 3) for row in rows: for col in cols: print(row, col) >>> 1 1 >>> 1 2 >>> 2 1 >>> 2 2 >>> 3 1 >>> 3 2 

    3 answers 3

    The rows iterator generates three elements on demand — 1, 2, 3 ; the cols iterator cols two elements — 1 и 2 :

     >>> range(1,4) [1, 2, 3] >>> range(1,3) [ 1, 2] 

    The for loop works like this: first, for each rows all the cols values ​​are cols , i.e. for 1 from rows all cols values ​​are 1 and 2:

     >>> 1 1 >>> 1 2 

    then for the next element from rows - deuces - all values ​​of cols :

     >>> 2 1 >>> 2 2 

    and so on.

    Read more here .

    • one
      rows - not a list, your answer is not about that version of python - andreymal
    • @andreymal, thank you for your comment, corrected - Ksenia

    For each fixed row value, the value of the variable col in the inner loop takes values ​​from the range [1, 3)

       rows = range(1, 4) # Конструкцию for можно применить к любому объекту(rows), имеющему атрибут __iter__ print(rows.__iter__) # <method-wrapper '__iter__' of range object at 0x032C1770> # У объекта вызывается rows.__iter__(), который возвратит объект, имеющий атрибут __next__ irs = rows.__iter__() print(irs) # <range_iterator object at 0x032C17E8> print(irs.__next__) # <method-wrapper '__next__' of range_iterator object at 0x02DA17E8> # На каждом этапе итерации цикла for, у объект-iterator будет вызван .__next__(), # который будет возвращять элементы rows-объекта, результат записывается в переменную(row) print(irs.__next__()) # 1 # при достижении конца rows-объекта, .__next__() вернет raise StopIteration # произойдет выход из for (StopIteration для циклов тоже самое что и break) print(irs.__next__()) # 2 print(irs.__next__()) # 3 try: print(irs.__next__()) # выдавать уже нечего except StopIteration: print('значения закончились') # примерно так и работает цикл for for row in rows: print(row)