itachi Uchiha
itachi Uchiha

Reputation: 23

List value changes after execution of for loop

I have a list "a". after executing following for loop list values are changed

a=[1,2,3]
for a[0] in a:
    print(a[0])


print(a) #it prints [3, 2, 3]

Upvotes: 1

Views: 746

Answers (3)

Jeronimo
Jeronimo

Reputation: 2397

Here's what your code does split up in single commands. Maybe this way you can better understand what's going on:

a = [1,2,3] 
# for loop begins
a[0] = a[0]    # a is now [1,2,3]
print(a[0])    # prints 1
a[0] = a[1]    # a is now [2,2,3]
print(a[0])    # prints 2
a[0] = a[2]    # a is now [3,2,3]
print(a[0])    # prints 3
# for loop ends
print(a)       # prints [3,2,3]

In short: don't ever use an element of a list as a loop variable to iterate over that list with. It makes no sense, except for very special cases.

Upvotes: 0

Shivam Singh
Shivam Singh

Reputation: 1624

When you write

for i in [1,2,3]:
    print i

i = 1 and then 2 and then 3 for each iteration. So if you execute this code

a=[1,2,3]
for a[0] in a:
    print a[0]
    print a

Output:

1
[1, 2, 3]
2
[2, 2, 3]
3
[3, 2, 3]

You can clearly see that a[0] is first 1, then 2 and finally 3, so 'a' becomes [1,2,3] in the end.

Upvotes: 1

dbaxime
dbaxime

Reputation: 816

I think you want to display all the values ​​in your list. If that's what you want to do, I advise you to use enumerate like this.

a=[1,2,4]
for index, value in enumerate(a):
        print(value)
print(a)

So no value in your list is changed.

Upvotes: 0

Related Questions