Using For Loop To Remove Elements From A List Is Not Working, But Using List Comprehension Is Fine
Solution 1:
These two methods are not identical. In the list comprehension, you never call adj.remove(z)
.
The list comprehension is creating a new list as it iterates over adj
, then you assign that (empty) list back to adj
once it's done. It doesn't change adj
while iterating, only after the last iteration.
Solution 2:
You can definitely use .remove()
, but iterate over a copy of the original and not the original itself:
adj = [[1, True], [0, 2, True], [1, True]]
for z in adj[:]:
print("for loop: ", z)
if z[-1] is True:
adj.remove(z)
result += 1
print("adj after all execution: ", adj)
which prints out an empty list.
Here, we iterate over the copy, but remove elements from the original. This avoids discrepancy that you see with your code.
Solution 3:
Iteration over the list
and at same time with it's inner block, if you use method remove
or append
for an element is not right way to do it. Basically better to change the coding to other way. As like Austin suggested in his code or use separate index instead of iterative index or element.
That is
adj = [[3, 4, 5, False], [8, 7, False], [0, True], [-1, False], [1, True], [0, 2, False], [0, 2, True], [1, True], [4, False]]
del_index = 0
for i in range(len(adj)):
print("for loop: ", adj[del_index])
if adj[del_index][-1] is True:
adj.remove(adj[del_index])
else:
del_index+=1
print("adj after all execution: ", adj)
Filter can applied for this purpose
filter(lambda elem: elem[-1] is True, adj)
This may crash your system since the append element to the list and same time iterating over the same.
crash_my_system = [0]
for i in crash_my_system: crash_my_system.append(i+1)
This is not only true for List
. this is common to all mutable data structure such as Dict
. Refer: Christoph Zwerschke's blog
Post a Comment for "Using For Loop To Remove Elements From A List Is Not Working, But Using List Comprehension Is Fine"