Python – using two for loops in python

combinationsfor-looppython

I have started to learn python recently and have a question about for loops that I was
hoping someone could answer. I want to be able to print all the possible products of two numbers from one to ten. so: 2 by 2, 2 by 3, 2 by 4…2 by 10, 3 by 2, 3 by 3…3 by 10, 4 by 2, 4 by 3 etc…I would have thought the easiest way to do so would be to use two for loops but I am not sure. could anyone please tell me how this is done.

Best Solution

Here is another way

a = [i*j for i in xrange(1,11) for j in xrange(i,11)]

note we need to start second iterator from 'i' instead of 1, so this is doubly efficient

edit: proof that it is same as simple solution

b = []
for i in range(1,11):
    for j in range(1,11):
        b.append(i*j)

print set(a) == set(b)