-1

The following example seems to indicate that the integrity of "for" is questionable. Please note that 'c' is not in 'words', yet is not removed from list.

phrase = "Don't panic!"
plist = list(phrase)
words = 'on tap'
for char in plist:
    # if the char from plist is not in words, then remove it from plist
    if char not in words:
        plist.remove(char)
    else:
        pass

print(plist)
['o', 'n', 't', ' ', 'p', 'a', 'n', 'c']

I understand what is happening - the initial state of 'for' sequence is not preserved: the iteration is not consistent.

Maybe it's me. However, same logic as implemented in tcl produces a result that reflects the intent of 'foreach' iteraction:

o n t ' ' p a n

Please advise on what I am missing about Python iteration. Rick

j1-lee
  • 13,764
  • 3
  • 14
  • 26

1 Answers1

1

You shouldn't modify a collection while you're iterating over it. Make a new array and push the desired elements into it.

phrase = "Don't panic!"
plist = list(phrase)
words = 'on tap'
result = []
for char in plist:
    if char in words:
        result.append(char)

print(result)

outputs ['o', 'n', 't', ' ', 'p', 'a', 'n']

Tyler Liu
  • 989
  • 1
  • 6
  • 7
  • First, thank you for the reply. After about an hour of introspection and debugging, I figured that out. However, could not find any docs that would indicate such a restriction. – 2Wheeldogs Jan 31 '22 at 03:57
  • @2Wheeldogs Maybe what you are looking for is the note for `for`: https://docs.python.org/3.9/reference/compound_stmts.html#the-for-statement: "*There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, e.g. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. ... This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated).*" – Gino Mempin Jan 31 '22 at 04:00
  • First, thank you for the reply. After about an hour of introspection and debugging, I figured that out. The point of posting was to see if what I had learned was consistent with others knowledge of the command. Am Just learning the language and find this disconcerting, particularly since I could not locate any docs that relate the operational limitations. I am a long time .net and tcl\tk developer and find this lack of tautology is new to me. – 2Wheeldogs Jan 31 '22 at 04:05
  • Thanks to all. I really want to like this language. – 2Wheeldogs Jan 31 '22 at 04:06
  • to Gino..that is exactly what I saw when debugging...and assumed to be true. I will need to read the docs in more detail. Those I found on the .org where superficial. – 2Wheeldogs Jan 31 '22 at 04:07