Iterating in two consecutive elements that will both return True on a list using "if" statement if the first one is already True | SoloLearn: Learn to code for FREE!

+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 """

3/30/2020 4:02:27 AM

Yves Manalo

3 Answers

New Answer

+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

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)

0

My solutions https://code.sololearn.com/cPED5QL1hem0/?ref=app