-1

Pyhton 3.10 on Windows (Python Launcher for Windows Version 3.10.4150.1013) seems to be skipping every other variable in a list inside a for loop:

plist = ['a','c','d','f','g','i','k','m']
removables = ['c','d','f','g','i','k','m']
def test():
    for letter in plist:
        if letter in removables:
            plist.remove(letter)
            print(plist)
test()
['a', 'd', 'f', 'g', 'i', 'k', 'm']
['a', 'd', 'g', 'i', 'k', 'm']
['a', 'd', 'g', 'k', 'm']
['a', 'd', 'g', 'k']

The behavior seems to be:

a 
c REMOVE ------ c 
d SKIP   ------ d 
f REMOVE ------ f 
g SKIP   ------ g 
i REMOVE ------ i
k SKIP   ------ k 
m REMOVE ------ m 

Why? I don't expect the skips.

mkrieger1
  • 14,486
  • 4
  • 43
  • 54
Hank Lenzi
  • 67
  • 1
  • 3
  • Thank you for you kind answer in explaining this so well and not dismissing me as a complete idiot. I would note that this little (now obvious) quirk is skipped over (pun intended) in many introductory Python courses (would mention them by name, but they're from big companies, so I won't give them free advertisement). – Hank Lenzi Jun 02 '22 at 15:07
  • It's not like we've been lacking that kind of explanation either… https://stackoverflow.com/a/6260097/476, https://stackoverflow.com/q/61139059/476 It's even in the official docs: https://docs.python.org/3.9/reference/compound_stmts.html#the-for-statement – deceze Jun 02 '22 at 15:10
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/245268/discussion-on-question-by-hank-lenzi-python-3-10-for-loop-is-skipping-test-varia). – deceze Jun 02 '22 at 15:13
  • The documentation mentioned "nasty bugs". I will not say more.... – Hank Lenzi Jun 02 '22 at 15:20
  • The conclusion is: do not iterate (via "for loop") on the (mutable) list (the list you want to change). So that a better idea is to iterate on the *other* list (the "removables" list), like so: `def test(): for letter in removables: if letter in plist: plist.remove(letter) print(plist) ` – Hank Lenzi Jun 03 '22 at 12:01

0 Answers0