0
H=[1,2,3,4,5,6,7,8]
for h in H:
    print h
    if h%2==1:
        H.remove(h)
        print H

Output:

1
[2, 3, 4, 5, 6, 7, 8]
3
[2, 4, 5, 6, 7, 8]
5
[2, 4, 6, 7, 8]
7
[2, 4, 6, 8]

So, I was just experimenting with the posibility of modifying a list inside a for loop over the same list, and while the list itself behaves like I thought, I don't get why the numbers 2,4,6,8 aren't being printed. Can anyone explain?

Diego
  • 233
  • 1
  • 3
  • 9
  • In your output `[2, 4, 6, 8]` **is** printed... Am I misunderstanding your question? – Reedinationer Apr 02 '19 at 23:59
  • 2
    it is bad practice to modify a list you are looping over – gold_cy Apr 03 '19 at 00:00
  • @aws_apprentice I've done it before, but I usually do it in reverse so the indexes don't get messed up. It's a bit messy, but certainly doable! – Reedinationer Apr 03 '19 at 00:00
  • 2
    that's a poor argument though, just because you _can_ do something in python does not mean it is _proper_ or the _recommended_ way to do it – gold_cy Apr 03 '19 at 00:01
  • If you are deliberately trying to modify the list while iterating through it, your best bet is to undo the effect of removing the element while the list index monotonously progresses forward. So when you are removing an element, try reducing the index by 1. Of course this means that you will have to use `enumerate()` which generates index as well as the element. – perennial_noob Apr 03 '19 at 00:04

1 Answers1

0

This is because you are modifying the list as your iterating through it. For ex, in your first iteration you are removing the element 1 and in your next iteration the index is 2. But in your modified list the element in index position 2 is 3 because you removed element 1.

perennial_noob
  • 459
  • 3
  • 14