What wrong with this? Why the output not is ["p","y","t","h","o","n"] | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

What wrong with this? Why the output not is ["p","y","t","h","o","n"]

stg=list(" py th on ") for c in stg: if c is " ": stg.remove(" ") print(stg)

26th Apr 2019, 10:55 AM
ⵢⴷⵢⴷ
ⵢⴷⵢⴷ - avatar
7 Respuestas
+ 6
You're changing the list while you're iterating over it. That's generally not a good idea. You can use a print statement in the for loop to see how the list changes dynamically
26th Apr 2019, 11:44 AM
Anna
Anna - avatar
+ 5
Gordon My answers are still several pages long if you display them on a very small screen 😏
26th Apr 2019, 12:33 PM
Anna
Anna - avatar
+ 4
Anna, you changed🤭. You used to give very detailed explanation in each step. Page length answers.
26th Apr 2019, 12:30 PM
Gordon
Gordon - avatar
+ 4
you could also use: stg=list(" py th on ") print(list(filter(lambda x: x != ' ', stg)))
26th Apr 2019, 3:37 PM
Lothar
Lothar - avatar
+ 3
stg = [c for c in stg if c != ' '] or: stg=list(" py th on ") while ' ' in stg: stg.remove(" ")
26th Apr 2019, 1:21 PM
Anna
Anna - avatar
+ 1
Thanks for the answers!😁
26th Apr 2019, 12:47 PM
ⵢⴷⵢⴷ
ⵢⴷⵢⴷ - avatar
+ 1
I've solved my problem. Thanks again! https://code.sololearn.com/cyQMHg2nl5Ou/?ref=app
26th Apr 2019, 1:15 PM
ⵢⴷⵢⴷ
ⵢⴷⵢⴷ - avatar