eozzy
eozzy

Reputation: 68680

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

Upvotes: 2

Views: 505

Answers (5)

telliott99
telliott99

Reputation: 7907

You should make a second list:

>>> num_rev = num[:]
>>> num_rev.reverse()
>>> num_rev
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Then do something like:

>>> for n1,n2 in zip(num,num_rev): 
...     print(n1, n2)
... 
0 9
1 8
2 7
3 6
4 5
5 4
6 3
7 2
8 1
9 0

Upvotes: 0

ezod
ezod

Reputation: 7421

Do you mean like this?

num = list(str(1234567))
for i in range(len(num)):
    print(num[i], '\t', num[-(i+1)])

Output is:

1       7                       
2       6                       
3       5                       
4       4                       
5       3                       
6       2                       
7       1  

Upvotes: 1

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72755

Here's a feeble attempt. Is this the kind of thing you're looking for?

 for idx,i in enumerate(x):
     print(i,"\t",x[-(idx+1)])

Upvotes: 1

wich
wich

Reputation: 17127

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

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

Upvotes: 7

Rob Grant
Rob Grant

Reputation: 7348

Nothing to do with Python, but here it is in Haskell :)

myDie  = [1,2,3,4,5,6]
sevens = [ (x,y) | x <- myDie, y <- myDie, x+y == 7]

Upvotes: 0

Related Questions