0

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 
3
  • 6
    The first one sets a[0] to each element in a and prints it. The second one prints a[0] repeatedly. Commented Nov 29, 2021 at 22:45
  • 3
    In case it's not clear to you, neither of these examples is correct code (assuming that you did not mean to mutate the a list in the first example). Commented Nov 29, 2021 at 22:50
  • Also note that the first loop is changing the value of a each iteration so afterwards it will end up being [4,1,2,3,4]. Commented Nov 30, 2021 at 0:18

2 Answers 2

5

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) 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.