+ 1

Iterating in two consecutive elements that will both return True on a list using "if" statement if the first one is already True

x = "12helloworld34" y = list(x) z= ["1","2","3","4","5","6","7","8","9","0"] for obj in y: if obj in z: y.remove(obj) w = "".join(y) print(w) """ output = 2helloworld4 my desired output is "helloworld". I guess my problem is in line 5. When it iterates to the first element on the list and satisfy the if statement(True), it disregard the second element which also satisfies the if statement. But im still not sure if that really is the problem. Hope you can share some insights. TIA """

30th Mar 2020, 4:02 AM
Yves Manalo
Yves Manalo - avatar
3 odpowiedzi
+ 1
Yves Manalo you are iterating over the original list so when you remove the fist element of the list, the second element become the first element but the loop counter must read the second element of the loop so that's why it skips "2" FIX You can iterate over a copy of list(like rodwynnejones said) Or You can also create one copy explisitly like this👇 https://code.sololearn.com/cTP8q9Yf7ttz/?ref=app
30th Mar 2020, 4:18 AM
Arsenic
Arsenic - avatar
0
x = "12helloworld34" y = list(x) z= ["1","2","3","4","5","6","7","8","9","0"] for obj in y[:]: # <--- do this, iterate over a copy if obj in z: y.remove(obj) w = "".join(y) print(w)
30th Mar 2020, 4:14 AM
rodwynnejones
rodwynnejones - avatar
30th Mar 2020, 4:34 AM
Geek
Geek - avatar