Search code examples
pythonlistenumerate

Enumerating over list with strings gives wrong results


I was surprised to see that these two don't output the same results. Why is that?

For a list

numbers = ['01', '02', '03']
>>> for val in numbers:
...     print(val)
01
02
03

while

>>> for i, val in numbers:
...     print(val)
1
2
3

Solution

  • You are unintentionally unpacking your string into 2 variables:

    a, b = "xy"
    print(a)
    print(b)
    
    x
    y
    

    What you really want is actually enumerate them:

    for i, val in enumerate(numbers):
        print(val)
    
    01
    02
    03