0

How come one-line foreach removes alternative elements in list and not removes everything? or how is the implementation of the foreach loop?

aList = ['xyz', 1, 'zara', 2, 'xyz']
for i, ele in enumerate(aList):
    print(i, ele)
    aList.remove(ele)
print(aList)

0 xyz

1 zara

2 xyz

[1, 2]

glibdud
  • 7,550
  • 4
  • 27
  • 37
Mujtaba Aldebes
  • 123
  • 1
  • 7
  • hey @jpp, I don't think that's a very good dup target for this question – MoxieBall Jul 19 '18 at 17:01
  • @Jpp i didn't find the answer in what you consider as duplicate – Mujtaba Aldebes Jul 19 '18 at 17:06
  • @jpp I agree that one is better. I still think that neither of them really give a satisfactory answer as to why this goes wrong in the way it does, but unless OP specifically requests that, I am content assuming that they have fixed their problem with those answers – MoxieBall Jul 19 '18 at 17:07
  • @jpp I think this example using `enumerate` might be sufficiently weird to deserve its own answer – MoxieBall Jul 19 '18 at 17:11
  • 1
    @MoxieBall, Fair enough, I'll reopen. I do think OP needs to explain why the duplicate doesn't help them. Otherwise, this is zero-research. – jpp Jul 19 '18 at 17:11
  • [This](https://stackoverflow.com/questions/43152898/list-remove-skipping-an-item-in-a-list?noredirect=1&lq=1) might be a better dup target. I'm surprised I can't find an SO answer with a step-by-step of exactly why removing elements from a list while iterating makes things happen that people don't expect – MoxieBall Jul 19 '18 at 17:19
  • I think [this answer](https://stackoverflow.com/a/34238688/6779307) gives a pretty good explanation in the second excerpt it quotes. – Patrick Haugh Jul 19 '18 at 17:22
  • @PatrickHaugh not sure which you meant but I think [this](https://stackoverflow.com/a/1207427/9801728) is the one that OP needs to see. – MoxieBall Jul 19 '18 at 17:25
  • 1
    @MoxieBall I meant this one: https://stackoverflow.com/a/34238688/6779307 – Patrick Haugh Jul 19 '18 at 17:26
  • @jpp here's a proper dup target: https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list – MoxieBall Jul 19 '18 at 18:22
  • @MoxieBall, Yep fine (I can't close now that I've reopened). Main point is I can't think of an answer which doesn't repeat those others. `enumerate` isn't relevant here IMO, but I reopened in case someone wants to explain why it's not relevant. – jpp Jul 19 '18 at 18:44
  • @jpp you're right, enumerate isn't relevant, I was mistaken in thinking it was. – MoxieBall Jul 19 '18 at 18:46

1 Answers1

3

1st iteration, access to 1st element of array: ['xyz', 1, 'zara', 2, 'xyz'] removes xyz => [1, 'zara', 2, 'xyz']

2nd iteration, access to 2nd element of array: [1, 'zara', 2, 'xyz'] removes zara, because zara is now the 2nd element => [1, 2, 'xyz']

3rd and final iteration, access to 3rd element of array: [1, 2, 'xyz'] remove xyz => [1, 2]

RRT
  • 156
  • 2
  • 3