Loop "Forgets" to Remove Some Items

Answer

You're modifying the list you're iterating over, which is bound to result in some unintuitive behavior. Instead, make a copy of the list so you don't remove elements from what you're iterating through.

for char in textlist[:]:#shallow copy of the list# etc

To clarify the behavior you're seeing, check this out. Put print char, textlist at the beginning of your (original) loop. You'd expect, perhaps, that this would print out your string vertically, alongside the list, but what you'll actually get is this:

H ['H','e','y',' ','l','o','o','k',' ','W','o','r','d','s','!']
e ['H','e','y',' ','l','o','o','k',' ','W','o','r','d','s','!']['H','y',' ','l','o','o','k',' ','W','o','r','d','s','!']# !
l ['H','y',' ','l','o','o','k',' ','W','o','r','d','s','!']
o ['H','y',' ','l','o','o','k',' ','W','o','r','d','s','!']
k ['H','y',' ','l','o','k',' ','W','o','r','d','s','!']# Problem!!['H','y',' ','l','o','k',' ','W','o','r','d','s','!']
W ['H','y',' ','l','o','k',' ','W','o','r','d','s','!']
o ['H','y',' ','l','o','k',' ','W','o','r','d','s','!'] 
d ['H','y',' ','l','k',' ','W','o','r','d','s','!']
s ['H','y',' ','l','k',' ','W','o','r','d','s','!']!['H','y',' ','l','k',' ','W','o','r','d','s','!']Hy lk Words!

All python Questions

Ask your interview questions on python

Write Your comment or Questions if you want the answers on python from python Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---