Home > Enterprise >  Why for loop does do this with 2d list?
Why for loop does do this with 2d list?

Time:07-22

I was making some codes that repeat same text with variations, but I ran into a problem.

Here are some codes

tick = int(input("Start: "))
end = False
listname = []

while not end:
    a = input()
    if a == "skip":
        tick  = 1
    elif a == "end":
        end = True
    else:
        listname.append([tick, a])
        tick  = 1

for b in listname:
    print(str(b[0])   " something "   b[1])

And I input:

Start: 10
1
2
3
4
5
end

Then it printed:

10 something
11 something 1
12 something
13 something 2
14 something
15 something 3
16 something 
17 something 4
18 something
19 something 5
20 something

But I was expecting for:

10 something 1
11 something 2
12 something 3
13 something 4
14 something 5

Why this happened?

CodePudding user response:

It was IDE problem. No problem on command line. Thanks for help

CodePudding user response:

Your code is true and when i test it, this print desired output.

Run again

CodePudding user response:

You need tick =1 before listname.append([tick,a]) in your control statement. This will cause a to be 1 before it is added to the array.

  • Related