hlzl
hlzl

Reputation: 508

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

Upvotes: 3

Views: 192

Answers (5)

Umer Rana
Umer Rana

Reputation: 178

When you are taking string element of list in one variable. It completely assigns that element to one variable.

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

Here it gives you 1,2,3 because it's assigning string to two variables byte wise:

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

For Example:

Like this, When you are doing

a,b = "89"
print('a =', a)
print('b =', b)

It returns a=8 and b=9. I think now it's clear to you.

Upvotes: 1

Vicrobot
Vicrobot

Reputation: 3988

You're unpacking the string in two parts. First is assigned to i , and second to val.

You're doing something like this:

i, val = '01'

Instead try enumerate of python for enumeration.

See bytecode:

>>> import dis
>>> def foo(): a,b = 'ds'
... 
>>> dis.dis(foo)
  1           0 LOAD_CONST               1 ('ds')
              2 UNPACK_SEQUENCE          2         # <---
              4 STORE_FAST               0 (a)
              6 STORE_FAST               1 (b)
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE

Upvotes: 1

NAGA RAJ S
NAGA RAJ S

Reputation: 453

Try Enumerate the for loop

for i, val in enumerate(numbers):
    print(val)

Upvotes: 0

sahinakkaya
sahinakkaya

Reputation: 6056

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

Upvotes: 1

maciek97x
maciek97x

Reputation: 7280

The second loop unpacks each string into two chars. If you want to get something like

i val
0 01
1 02
2 03

then you should use enumerate.

for i, val in enumerate(numbers):
    print(i, val)

Upvotes: 1

Related Questions