Ertaku
Ertaku

Reputation: 51

"for" loops and iteration

Can you explain logic behind this? I can't understand the difference between them.

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

    Output:

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

    Output:

    0
    0
    0
    0
    0
    

Upvotes: 0

Views: 162

Answers (2)

Mohsen Karimi
Mohsen Karimi

Reputation: 129

First, it is worth noting that changing an iterator while iterating over it is not recommended (as you do in the first example) because it can lead to unexpected behavior in some cases. For example, the following code can lead to an unlimited loop:

a = [0,1,2,3,4]
for x in a:
    print(x)
    a.append(5)  # changing the iterator

In the first case, in each iteration, you are assigning the iterated value to the first element of your list (i.e a[0]) so you are changing the iterator. In the second case, you are assigning the iterated value to variable x but not using it and only printing the first element of your list.

Upvotes: 0

Kirk Strauser
Kirk Strauser

Reputation: 30957

In the first case:

for a[0] in a:
        print(a[0])

For each item in a, you're storing its value in a[0], then printing the contents of that list index. Afterwards, a will have the value [4, 1, 2, 3, 4].

Now on the second loop:

for x in a:
     print(a[0])

For each item in a, you're storing its contents in a new variable called x, which you then ignore. You're printing a[0] which will always have the same value because you're not doing anything to update it.

The most common way of looping is:

for x in a:
     print(x)

Upvotes: 5

Related Questions