Home > Net >  Traverse a list in two ways but can't understand the behavior
Traverse a list in two ways but can't understand the behavior

Time:04-23

The first one is:

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

Output:

1
2

My interpretation is that when the index i comes to the second element (2), the list only keeps [1, 2]. And then for the third run of loop, there's no element left to traverse.

However, when I keep the concept which I describe above and then tried the following code, the outcome doesn't make sense to me at all.

d = [1,2,3,4]
for i in d:
    *d, f = d
    print(i)

Output:

1
2
3
4

Hope someone can help me figure out the correct concept and go through the details.

CodePudding user response:

The d can refer to different objects. For example, try running this code:

d = [1,2,3,4]
print("Original id:", id(d))

for i in d:
    *d, f = d
    print("Changed id:",id(d))

The output is:

Original id: 140070366186944
Changed id: 140070365563072
Changed id: 140070365563200
Changed id: 140070365563072
Changed id: 140070365563200

As you can see, even though we are using the same variable, they are not referring to the same id. The array stored at the id that the for-loop is using will not be changed. The for-loop doesn't care what the array is called, it uses the id to find the array everytime. So if you create an array with the same name, nothing changes for the for-loop, because the array stored at the id that it originally had has not been changed.

Now try this code:

d = [1,2,3,4]
print("Original id:", id(d))

for i in d:
    d.pop()
    print("Changed id:",id(d))

You get the output:

Original id: 139873062706816
Changed id: 139873062706816
Changed id: 139873062706816

As you can see, the array that is being changed is the same. So the array that your for-loop is using changes everytime.

TLDR: d.pop() doesn't create copies; it changes the original array. *d, f = d creates a copy and changes that array, while the for-loop keeps using the original array that has not been changed.

CodePudding user response:

Okay, so in your first program you have your list with 1, 2, 3,4. Then your loop is gonna loop 4 times. So one the first iteration its gonna print 1 because thats what i is equal to. Then its gonna pop an item in the list and since its got nothing in the () its gonna automatically pop the last item which is 4. Then it loops again and prints 2 and pops the 3. This now means that on the third loop theres only 2 items in the list which is [1, 2] so the loops ends because it has succeeded the length of the list. Then in the 2nd program its once again gonna loop 4 times and the first line says that f = d so the first loop will mean that f = 1 then it will print 1 because i = 1. It will proceed to just print 1-4 because i isnt a changing variable and d-list isnt changing. Lol long response but meh

  • Related