Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23276

Does a for loop check if you are at the end of the iterable each iteration?

$
0
0

I am new to coding so for practice I was making a function that removes all of a certain character from any string passed into the function. I found that my for loop was not working as expected. It was not removing every '.'.

lst = ['.','.']for item in lst:    if item == '.':        lst.remove('.')print(lst)

Which outputs: ['.']

After trying different inputs and thinking about this, I came to the conclusion that a for loop will check if it is at the end of the list every iteration of the loop. Otherwise this loop would give an index error. As on the first iteration of the loop, the index of the loop is 0. It then removes the first '.', which leaves the list ['.']. Now on the second iteration index is 1, but list only has one element. So loop is out of index.

Is this true, or am I missing something?


Viewing all articles
Browse latest Browse all 23276

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>