Say I have a 2d list like this:
list = [[1, 2, 3], ["a", 5, 6], [7, 8, 9], [10, 11, 12]]
and I want to delete a list that starts with a. Here is what I tried:
for i in range(0, len(list)):
if list[i][0] == "a":
list.pop(i)
Run Code Online (Sandbox Code Playgroud)
Here, I am trying to delete a list that starts with a. However, it gives me an error saying
IndexError: list index out of range
I am not sure what the problem is here. It's weird because when I try print(list[i]), it prints the matching line, which is `["a", 2, 3].
I am expecting list = [[1, 2, 3], [7, 8, 9], [10, 11, 12]] as my final list.
Use a list comprehension:
>>> l = [[1, 2, 3], ["a", 5, 6], [7, 8, 9], [10, 11, 12]]
>>> new_l = [sublist for sublist in l if sublist[0] != 'a']
>>> new_l
[[1, 2, 3], [7, 8, 9], [10, 11, 12]]
Run Code Online (Sandbox Code Playgroud)
通常,在内置变量(list)后面命名变量不是一个好主意,因为您会遮盖这些内置变量。
而且,正如其他人所指出的那样,您最初的问题是list在迭代过程中进行变异。