The for loop is supposed to go through a list and add the elements to another list until it encounters an empty string. However, it keeps jumping over the second element.
The for-loop is supposed to go through a list("baa"), adding every element to a different list("foo"), until it encounters an empty string. At that point it is supposed to print out both of the lists. However for some reason the loop keeps jumping over the second element of my list, not adding it to "foo". I have no clues on any fixes or alternatives.
Code:
baa = ["1","2","","3","","4"]
foo=[]
for o in baa:
baa.remove(o)
if o =="":
break
else:
print(o)
print(baa)
print(foo)
Output:
['2', '3', '', '4'] ['1']
CodePudding user response:
for o in baa:
baa.remove(o)
You're adding/removing items in a list at the same time you're iterating over it.
This causes odd behavior exactly as you are seeing.
Don't do that.
CodePudding user response:
Try:
baa = ["1","2","","3","","4"]
original_baa = baa.copy()
foo=[]
for o in original_baa:
baa.remove(o)
if o == "":
break
else:
foo.append(o)
print(baa)
print(foo)
This avoids removing an item from a list that you're looping over, by first taking a copy that's not modified.
This also assigns the values to foo
as the loop progresses.
You can also do this using index
and without looping / explicitly removing items:
baa = ["1","2","","3","","4"]
try:
foo = baa[baa.index("") 1:]
baa = baa[:baa.index("")]
except ValueError:
foo = []
print(baa)
print(foo)
The try...except
is for the case when baa
does not contain any ""
.