How to remove list elements in a for loop in Python?
You are not permitted to remove elements from the list while iterating over it using a for
loop.
The best way to rewrite the code depends on what it is you're trying to do.
For example, your code is equivalent to:
for item in a:
print(item)
a[:] = []
Alternatively, you could use a while
loop:
while a:
print(a.pop())
I'm trying to remove items if they match a condition. Then I go to next item.
You could copy every element that doesn't match the condition into a second list:
result = []
for item in a:
if condition is False:
result.append(item)
a = result
Alternatively, you could use filter
or a list comprehension and assign the result back to a
:
a = filter(lambda item:... , a)
or
a = [item for item in a if ...]
where ...
stands for the condition that you need to check.
How to remove items from a list while iterating?
You can use a list comprehension to create a new list containing only the elements you don't want to remove:
somelist = [x for x in somelist if not determine(x)]
Or, by assigning to the slice somelist[:]
, you can mutate the existing list to contain only the items you want:
somelist[:] = [x for x in somelist if not determine(x)]
This approach could be useful if there are other references to somelist
that need to reflect the changes.
Instead of a comprehension, you could also use itertools
. In Python 2:
from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)
Or in Python 3:
from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)
Python: How to remove elements from list while iterating through it without skipping future iterations
You are right. You need an additional list. But there is an easier solution.
def print_numTXTs(fileList):
counter = 0
for file in list(fileList):
if file.name[-4:] == ".txt":
counter +=1
if file.name == "a.txt":
fileList.remove(file)
The secret is "list(fileList)". You creating an additional list and iterates over this.
Just as powerful are list compressions. In your example it should work like this. I have not tried now...only quickly written here.
fileList = [ file for file in fileList if file.name != "a.txt" ]
Remove element from list of lists during loop
You need to make copy of original list and then iterate over new copy and remove the items from original list
for item in list(original_list):
...
original_list.remove(item)
In your case, code will look like below
total_read = 0
for i in range(21):
random.shuffle(info)
for index, value in enumerate(list(info)):
b, p, s = value
if len(s) <= i+1:
print("Overshot! Shouldn't see this sentence anymore: %s" % (s))
info.pop(index)
print s[:i+1], i, s
total_read += len(s[i + 1])
About removing an item from a list with a for loop
The second code works because a new list is created with list(a)
. You then iterate through the new list and remove items from the original list.
The second code is acceptable in the sense that you are not iterating through the same list you are modifying.
Removing element from a list in a for loop
It's not a good idea to remove elements from a list while looping through it. You can always make a copy and update it:
import copy
my_list= copy.deepcopy(master_list)
However, a better approach would be to use list comprehensions:
master_list = [{"irrelevant_key": "irrevelant_value",
"relevant_key":
[[{"first_value": "first_key"}, {"problem_key": 0}],
[{"second_value": "second_key"}, {"problem_key": 1}]],
}]
for lst in master_list:
lst['relevant_key'] = [x for x in lst['relevant_key'] if x[1]['problem_key'] != 0 ]
nested looping to remove items in list
Your logic is confused, why are your iterating over the removal list, del1
, and then within that iterating over s
(or l
).
This makes no sense.
Instead, just remove elements from del1
, as you go.
l = [1,5,10,5,10]
del1 = [5,10]
a = []
for element in l:
if element in del1:
del1.remove(element)
else:
a.append(element)
giving a
as [1, 5, 10]
.
A more efficient way is to use a collections.Counter
object.
import collections
l = [1,5,10,5,10]
del1 = [5,10]
a = []
dels_to_go = collections.Counter(del1)
for element in l:
if dels_to_go[element]:
dels_to_go[element] -= 1
else:
a.append(element)
which gives the same output as before.
Note, you may be tempted to use a set()
, but this would not work in the case of del1
containing repeated values.
Python: Removing list element while iterating over list
You could always iterate over a copy of the list, leaving you free to modify the original:
for item in list(somelist):
...
somelist.remove(item)
Related Topics
Calling a Function Upon Button Press
Web Scraping Program Cannot Find Element Which I Can See in the Browser
Use Groupby in Pandas to Count Things in One Column in Comparison to Another
Can One Get Hierarchical Graphs from Networkx with Python 3
How to Get Tkinter Canvas to Dynamically Resize to Window Width
Django Query That Get Most Recent Objects from Different Categories
How Do Python Functions Handle the Types of Parameters That You Pass In
How to Disable SQLalchemy Caching
What Is the Most Compatible Way to Install Python Modules on a MAC
Flask-Sqlalchemy Import/Context Issue
Numpy: Get Random Set of Rows from 2D Array
How to Timeout Function in Python, Timeout Less Than a Second
How to Extract Frequency Associated with Fft Values in Python
How to Make a Barplot and a Lineplot in the Same Seaborn Plot with Different Y Axes Nicely
Python Ftp Implicit Tls Connection Issue
Why Do Attribute References Act Like This with Python Inheritance