이종연
이종연

Reputation: 119

Why is my list not reiterating when I put a double loop on python

So I am trying to create a multiplication table from 2 to 9, for some reason when I put a double for loop it shows the following. I am thinking it's because, after the initial loop, the next loop simply starts at the [3] instead of [2]. Am I correct? if so, why is that? I thought the iteration should start from [2] element on the second loop and go back to the first loop.

numbers = map(int,range(2,10))
for numone in numbers: 
    for numtwo in numbers:
        print('{0}*{1}={2}'.format(numone,numtwo,numone*numtwo))


Result 
2*3=6
2*4=8
2*5=10
2*6=12
2*7=14
2*8=16
2*9=18

Upvotes: 0

Views: 53

Answers (1)

enzo
enzo

Reputation: 11496

It's because when you use map, you're using a iterator. And iterators only go forward. Ever.

There's no need for map, you can just use range:

numbers = range(2,10)
for numone in numbers: 
    for numtwo in numbers:
        print('{0}*{1}={2}'.format(numone,numtwo,numone*numtwo))
    print()

The code above shows the expected output because range is an iterable and can restart iteration.

Upvotes: 2

Related Questions