Search code examples
pythonloopsfor-loopreverse

Reverse loop inside a loop with same list


num = list(str(1234567))

for n1 in num:
    print(n1)
    for n2 in reversed(num):
        print('\t', n2)

On each iteration, it prints the first digit from the first loop and all 7 from the reverse loop. How can I print not all digits but only the last (i.e first) digit from reverse loop?

Thanks


Solution

  • Simplest way is to just zip the forward and reverse lists together:

    for n1, n2 in zip(num, reversed(num)):
        print(n1, '\t', n2)