def str_to_list(str):
# Insert your code here
new = list(str)
for i in new:
if i == or (i.isdigit() and int(i) > 5):
new.remove(i)
return new
I expect out to be ['d', 'o', 'l', 'l', 'a', 'r']
But I get [' ', 'd', 'o', 'l', 'l', 'a', 'r']
I suppose there was a typo
if i == or (i.isdigit() and int(i) > 5)
As this should result into a syntax error.
So I guess it was meant to be?
if i == " " or (i.isdigit() and int(i) > 5)
In that case, I would suspect that it is due to indices in your array getting shifted while you were iterating over it and at the same time removing elements from it. It is generally not recommended to modify a list in such a way that indices shift, while iterating over it. Like in this example, where you are trying to remove spaces and specific numbers. And it would mean that after removing the "5" from array, you are ended up with two " " str spaces in your array. But iterator is not going to reset it's counter. It only does a number of iterators that was determined at the very start of the process. So there are not resets to previous positions. But at the same time we are being left with a our " " " str which ended up there after "6" was removed. It basically shifted it position to the one that "6" had before. While spefici checks were perfmored at the position from which " " had moved away. Tried my best to explain it. But yeah, there is a reason why it is considered a bad practice. It really makes things difficult to follow. Well it does for me for sure. Instead I would suggest something like this:
def str_to_list(x):
formatted = [i for i in [s for s in list(x)
if not(s.isdigit() and int(s) > 5)]
if not i.ispace()]]
return formatted
or less concise, but easier to follow:
def str_to_list(x):
new_lst = []
for i in list(x):
if i.isspace():
pass
elif (i.isdigit() and int(i) > 5):
pass
else:
new_lst.append(i)
return new_lst
It is a much more safer option and makes the whole thing less complicated in general if instead there is new array prepared while iterating over the original one.
I hope it helped.