Print all numbers from second list before printing next number from another

Viewed 44

I want to complete two I in range statements, Start with the first I in Range let it complete the second I In Range statement then move to the second pid.

For example below code prints:

1
222
2
233
3
333
1
222
2
233
3
333
1
222
2
233
3
333

Where as i would like it to print: 1 222 233 333 2 222 233 333 and so on

pid = ["1", "2", "3"]
store = ["222", "233", "333"]

for i in range(len(pid)):
    for i in range(len(store)):
        print (format(pid[i]))
        print (format(store[i]))
2 Answers

One print for outer for-loop and one for inner for-loop.

pid = ["1", "2", "3"]
store = ["222", "233", "333"]
for i in pid:
    print(i)
    for j in store:
        print(j)

You have to print the element of pid every time befor you iterate over every element in store

This is the most similar to your code:

for i in range(len(pid)):

    print (format(pid[i]))

    for i in range(len(store)):
        print (format(store[i]))

More elegant is to not use len() and to not use the same name variable name twice:

for i in pid:
    print(i)
    for j in store:
        print(j)
   

I hope you learned something new :)

Related