Home > Software design >  Using the last element of a list as the item for a for-loop
Using the last element of a list as the item for a for-loop

Time:08-02

Sorry for the cumbersome worded question, but given the following array:

x = [1,2,3,4]

When I loop through it using the first index with the following loop:

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

I get the following expected result:

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

However, when I execute the following loop using the last index of x:

for x[-1] in x:
    print(x)

I would expect to get the following, call it 'result 1' (My current thought process is that for each iteration, the value of the current iteration replaces the last element of x):

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

But instead, I get this, call it 'result 2':

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

Can someone explain why I am getting 'result 2'? I don't understand why I am getting 'result 2' instead of 'result 1'?

EDIT: Sorry nums was suppose to be called x.

CodePudding user response:

Your loop is effectively equivalent to:

x[3] = x[0]
print(x)
x[3] = x[1]
print(x)
x[3] = x[2]
print(x)
x[3] = x[3]
print(x)

The last iteration doesn't change anything, since it's assigning an element to itself.

To get your expected results, you can do:

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

x[:] makes a copy of x, so you're not modifying the same list you're iterating over.

CodePudding user response:

for x[-1] in x: assigns the iterated values to the last element of the list, in turn. By the time you iterate that last value, you've already changed it to '3`, so that's what you get.

  • Related