How do I remove an element from a list by index in Python?
如何用Python中的索引从列表中删除元素?
I found the list.remove
method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.
我发现这个列表。删除方法,但是如果我想删除最后一个元素,我该怎么做呢?看起来默认的删除搜索列表,但是我不希望执行任何搜索。
16 个解决方案
#1
1179
Use del
and specify the index of the element you want to delete:
使用del并指定要删除的元素的索引:
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Also supports slices:
还支持片:
>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]
Here is the section from the tutorial.
这是本教程的一部分。
#2
478
You probably want pop
:
你可能想要流行:
a = ['a', 'b', 'c', 'd']
a.pop(1)
# now a is ['a', 'c', 'd']
By default, pop
without any arguments removes the last item:
默认情况下,不带任何参数的pop删除最后一项:
a = ['a', 'b', 'c', 'd']
a.pop()
# now a is ['a', 'b', 'c']
#3
95
Like others mentioned pop and del are the efficient ways to remove an item of given index. Yet just for the sake of completion (since the same thing can be done via many ways in Python):
和其他提到的pop和del一样,它们是删除给定索引项的有效方法。然而,仅仅是为了完成(因为在Python中,同样的事情可以通过多种方式来完成):
Using slices (this does not do in place removal of item from original list):
使用切片(不从原始列表中移除项目):
(Also this will be the least efficient method when working with Python list, but this could be useful (but not efficient, I reiterate) when working with user defined objects that do not support pop, yet do define a __getitem__
):
(在使用Python列表时,这也是效率最低的方法,但在使用不支持pop的用户定义对象时,这可能是有用的(但我重申一下,这不是有效的),但在定义__getitem__时,这是有用的):
>>> a = [1, 2, 3, 4, 5, 6]
>>> index = 3 # Only positive index
>>> a = a[:index] + a[index+1 :]
# a is now [1, 2, 3, 5, 6]
Note: Please note that this method does not modify the list in place like pop
and del
. It instead makes two copies of lists (one from the start until the index but without it (a[:index]
) and one after the index till the last element (a[index+1:]
)) and creates a new list object by adding both. This is then reassigned to the list variable (a
). The old list object is hence dereferenced and hence garbage collected (provided the original list object is not referenced by any variable other than a).
注意:请注意,此方法不像pop和del那样修改列表。相反,它生成两个列表副本(一个从开始到索引但没有它(一个[:index]),一个在索引之后,直到最后一个元素(一个[index+1:])),并通过添加这两个元素创建一个新的list对象。然后将其重新分配给列表变量(a),旧的列表对象因此被取消引用,从而被垃圾收集(前提是除了a之外的任何变量都不引用原始的列表对象)。
This makes this method very inefficient and it can also produce undesirable side effects (especially when other variables point to the original list object which remains un-modified).
这使得此方法非常低效,并且还可能产生不希望的副作用(特别是当其他变量指向仍未修改的原始列表对象时)。
Thanks to @MarkDickinson for pointing this out ...
感谢@MarkDickinson指出这一点……
This Stack Overflow answer explains the concept of slicing.
这个堆栈溢出回答解释了切片的概念。
Also note that this works only with positive indices.
还要注意,这只适用于正指标。
While using with objects, the __getitem__
method must have been defined and more importantly the __add__
method must have been defined to return an object containing items from both the operands.
在使用对象时,必须定义__getitem__方法,更重要的是,必须定义__add__方法,以从两个操作数返回包含项目的对象。
In essence, this works with any object whose class definition is like:
从本质上说,这适用于任何类定义如下的对象:
class foo(object):
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return foo(self.items[index])
def __add__(self, right):
return foo( self.items + right.items )
This works with list
which defines __getitem__
and __add__
methods.
这与定义__getitem__和__add__方法的列表一起工作。
Comparison of the three ways in terms of efficiency:
三种方式的效率比较:
Assume the following is predefined:
假设以下是预定义的:
a = range(10)
index = 3
The del object[index]
method:
德尔对象(指数)方法:
By far the most efficient method. It works will all objects that define a __del__
method.
到目前为止,这是最有效的方法。所有定义__del__方法的对象都可以使用它。
The disassembly is as follows:
拆卸工作如下:
Code:
代码:
def del_method():
global a
global index
del a[index]
Disassembly:
拆卸:
10 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 DELETE_SUBSCR # This is the line that deletes the item
7 LOAD_CONST 0 (None)
10 RETURN_VALUE
None
pop
method:
流行的方法:
It is less efficient than the del method and is used when you need to get the deleted item.
它比del方法效率更低,当您需要获取已删除的项时使用它。
Code:
代码:
def pop_method():
global a
global index
a.pop(index)
Disassembly:
拆卸:
17 0 LOAD_GLOBAL 0 (a)
3 LOAD_ATTR 1 (pop)
6 LOAD_GLOBAL 2 (index)
9 CALL_FUNCTION 1
12 POP_TOP
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
The slice and add method.
切片和添加方法。
The least efficient.
最有效的。
Code:
代码:
def slice_method():
global a
global index
a = a[:index] + a[index+1:]
Disassembly:
拆卸:
24 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 SLICE+2
7 LOAD_GLOBAL 0 (a)
10 LOAD_GLOBAL 1 (index)
13 LOAD_CONST 1 (1)
16 BINARY_ADD
17 SLICE+1
18 BINARY_ADD
19 STORE_GLOBAL 0 (a)
22 LOAD_CONST 0 (None)
25 RETURN_VALUE
None
Note: In all three disassembles ignore the last two lines which basically are return None
. Also the first two lines are loading the global values a
and index
.
注意:在这三种反汇编语言中,都忽略了最后两行,它们基本上是返回None。前两行还装载全局值a和索引。
#4
41
pop
is also useful to remove and keep an item from a list. Where del
actually trashes the item.
pop从列表中删除并保留一个条目也很有用。德尔实际上是在破坏物品。
>>> x = [1, 2, 3, 4]
>>> p = x.pop(1)
>>> p
2
#5
12
Generally, I am using the following method:
我一般采用以下方法:
>>> myList = [10,20,30,40,50]
>>> rmovIndxNo = 3
>>> del myList[rmovIndxNo]
>>> myList
[10, 20, 30, 50]
#6
9
This depends on what you want to do.
这取决于你想做什么。
If you want to return the element you removed, use pop()
:
如果要返回删除的元素,请使用pop():
>>> l = [1, 2, 3, 4, 5]
>>> l.pop(2)
3
>>> l
[1, 2, 4, 5]
However, if you just want to delete an element, use del
:
但是,如果您只想删除一个元素,请使用del:
>>> l = [1, 2, 3, 4, 5]
>>> del l[2]
>>> l
[1, 2, 4, 5]
Additionally, del
allows you to use slices (e.g. del[2:]
).
此外,del允许您使用切片(例如del[2:])。
#7
6
Yet another way to remove an element(s) from a list by index.
另一种从列表中按索引删除元素的方法。
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# remove the element at index 3
a[3:4] = []
# a is now [0, 1, 2, 4, 5, 6, 7, 8, 9]
# remove the elements from index 3 to index 6
a[3:7] = []
# a is now [0, 1, 2, 7, 8, 9]
a[x:y] points to the elements from index x
to y-1
. When we declare that portion of the list as an empty list ([]
), those elements are removed.
a[x:y]指向从索引x到y-1的元素。当我们将列表的那一部分声明为空列表([])时,这些元素将被删除。
#8
5
Use the following code to remove element from the list:
使用以下代码从列表中删除元素:
list = [1, 2, 3, 4]
list.remove(1)
print(list)
output = [2, 3, 4]
If you want to remove index element data from the list use:
如果要从列表中删除索引元素数据,请使用:
list = [1, 2, 3, 4]
list.remove(list[2])
print(list)
output : [1, 2, 4]
#9
5
You could just search for the item you want to delete. It is really simple. Example:
你可以搜索你想删除的条目。这是很简单的。例子:
letters = ["a", "b", "c", "d", "e"]
letters.remove(letters[1])
print(*letters) # Used with a * to make it unpack you don't have to (Python 3.x or newer)
Output: a c d e
输出:cde
#10
3
As previously mentioned, best practice is del(); or pop() if you need to know the value.
如前所述,最佳实践是del();或者pop()如果你需要知道它的值。
An alternate solution is to re-stack only those elements you want:
另一种解决方案是只重新堆叠你想要的元素:
a = ['a', 'b', 'c', 'd']
def remove_element(list_,index_):
clipboard = []
for i in range(len(list_)):
if i is not index_:
clipboard.append(list_[i])
return clipboard
print(remove_element(a,2))
>> ['a', 'b', 'd']
eta: hmm... will not work on negative index values, will ponder and update
埃塔:嗯……不会对负面的索引值工作,会思考和更新吗?
I suppose
我想
if index_<0:index_=len(list_)+index_
would patch it... but suddenly this idea seems very brittle. Interesting thought experiment though. Seems there should be a 'proper' way to do this with append() / list comprehension.
将补丁……但突然之间,这个想法显得非常脆弱。有趣的思想实验。似乎应该有一种“合适”的方法来使用append() /列表理解。
pondering
思考
#11
3
It doesn't sound like you're working with a list of lists, so I'll keep this short. You want to use pop since it will remove elements not elements that are lists, you should use del for that. To call the last element in python it's "-1"
这听起来不像是你在处理一份清单,所以我将保持这个简短。您希望使用pop,因为它将删除元素而不是列表元素,您应该使用del。要调用python中的最后一个元素,它是"-1"
>>> test = ['item1', 'item2']
>>> test.pop(-1)
'item2'
>>> test
['item1']
#12
3
Use the "del" function:
使用“▽”功能:
del listName[-N]
For example, if you want to remove the last 3 items, your code should be:
例如,如果您想删除最后3项,您的代码应该是:
del listName[-3:]
For example, if you want to remove the last 8 items, your code should be:
例如,如果您想删除最后8项,您的代码应该是:
del listName[-8:]
#13
1
l - list of values; we have to remove indexes from inds2rem list.
l -值列表;我们必须删除inds2rem列表中的索引。
l = range(20)
inds2rem = [2,5,1,7]
map(lambda x: l.pop(x), sorted(inds2rem, key = lambda x:-x))
>>> l
[0, 3, 4, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
#14
0
You can use either del or pop to remove element from list based on index. Pop will print member it is removing from list, while list delete that member without printing it.
您可以使用del或pop从基于索引的列表中删除元素。Pop将打印它正在从列表中删除的成员,而list删除该成员而不打印它。
>>> a=[1,2,3,4,5]
>>> del a[1]
>>> a
[1, 3, 4, 5]
>>> a.pop(1)
3
>>> a
[1, 4, 5]
>>>
#15
0
One can either use del or pop, but I prefer del, since you can specify index and slices, giving the user more control over the data.
可以使用del或pop,但我更喜欢del,因为您可以指定索引和片,从而使用户能够对数据进行更多的控制。
For example, starting with the list shown, one can remove its last element with del
as a slice, and then one can remove the last element from the result using pop
.
例如,从显示的列表开始,可以使用del作为一个切片来删除它的最后一个元素,然后可以使用pop从结果中删除最后一个元素。
>>> l = [1,2,3,4,5]
>>> del l[-1:]
>>> l
[1, 2, 3, 4]
>>> l.pop(-1)
4
>>> l
[1, 2, 3]
#16
-1
You can simply use the remove
function of Python. Like this:
您可以简单地使用Python的删除函数。是这样的:
v = [1, 2, 3, 4, 5, 6]
v.remove(v[4]) # I'm removing the number with index 4 of my array
print(v) # If you want verify the process
# It gave me this:
#[1,2,3,4,6]
#1
1179
Use del
and specify the index of the element you want to delete:
使用del并指定要删除的元素的索引:
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Also supports slices:
还支持片:
>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]
Here is the section from the tutorial.
这是本教程的一部分。
#2
478
You probably want pop
:
你可能想要流行:
a = ['a', 'b', 'c', 'd']
a.pop(1)
# now a is ['a', 'c', 'd']
By default, pop
without any arguments removes the last item:
默认情况下,不带任何参数的pop删除最后一项:
a = ['a', 'b', 'c', 'd']
a.pop()
# now a is ['a', 'b', 'c']
#3
95
Like others mentioned pop and del are the efficient ways to remove an item of given index. Yet just for the sake of completion (since the same thing can be done via many ways in Python):
和其他提到的pop和del一样,它们是删除给定索引项的有效方法。然而,仅仅是为了完成(因为在Python中,同样的事情可以通过多种方式来完成):
Using slices (this does not do in place removal of item from original list):
使用切片(不从原始列表中移除项目):
(Also this will be the least efficient method when working with Python list, but this could be useful (but not efficient, I reiterate) when working with user defined objects that do not support pop, yet do define a __getitem__
):
(在使用Python列表时,这也是效率最低的方法,但在使用不支持pop的用户定义对象时,这可能是有用的(但我重申一下,这不是有效的),但在定义__getitem__时,这是有用的):
>>> a = [1, 2, 3, 4, 5, 6]
>>> index = 3 # Only positive index
>>> a = a[:index] + a[index+1 :]
# a is now [1, 2, 3, 5, 6]
Note: Please note that this method does not modify the list in place like pop
and del
. It instead makes two copies of lists (one from the start until the index but without it (a[:index]
) and one after the index till the last element (a[index+1:]
)) and creates a new list object by adding both. This is then reassigned to the list variable (a
). The old list object is hence dereferenced and hence garbage collected (provided the original list object is not referenced by any variable other than a).
注意:请注意,此方法不像pop和del那样修改列表。相反,它生成两个列表副本(一个从开始到索引但没有它(一个[:index]),一个在索引之后,直到最后一个元素(一个[index+1:])),并通过添加这两个元素创建一个新的list对象。然后将其重新分配给列表变量(a),旧的列表对象因此被取消引用,从而被垃圾收集(前提是除了a之外的任何变量都不引用原始的列表对象)。
This makes this method very inefficient and it can also produce undesirable side effects (especially when other variables point to the original list object which remains un-modified).
这使得此方法非常低效,并且还可能产生不希望的副作用(特别是当其他变量指向仍未修改的原始列表对象时)。
Thanks to @MarkDickinson for pointing this out ...
感谢@MarkDickinson指出这一点……
This Stack Overflow answer explains the concept of slicing.
这个堆栈溢出回答解释了切片的概念。
Also note that this works only with positive indices.
还要注意,这只适用于正指标。
While using with objects, the __getitem__
method must have been defined and more importantly the __add__
method must have been defined to return an object containing items from both the operands.
在使用对象时,必须定义__getitem__方法,更重要的是,必须定义__add__方法,以从两个操作数返回包含项目的对象。
In essence, this works with any object whose class definition is like:
从本质上说,这适用于任何类定义如下的对象:
class foo(object):
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return foo(self.items[index])
def __add__(self, right):
return foo( self.items + right.items )
This works with list
which defines __getitem__
and __add__
methods.
这与定义__getitem__和__add__方法的列表一起工作。
Comparison of the three ways in terms of efficiency:
三种方式的效率比较:
Assume the following is predefined:
假设以下是预定义的:
a = range(10)
index = 3
The del object[index]
method:
德尔对象(指数)方法:
By far the most efficient method. It works will all objects that define a __del__
method.
到目前为止,这是最有效的方法。所有定义__del__方法的对象都可以使用它。
The disassembly is as follows:
拆卸工作如下:
Code:
代码:
def del_method():
global a
global index
del a[index]
Disassembly:
拆卸:
10 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 DELETE_SUBSCR # This is the line that deletes the item
7 LOAD_CONST 0 (None)
10 RETURN_VALUE
None
pop
method:
流行的方法:
It is less efficient than the del method and is used when you need to get the deleted item.
它比del方法效率更低,当您需要获取已删除的项时使用它。
Code:
代码:
def pop_method():
global a
global index
a.pop(index)
Disassembly:
拆卸:
17 0 LOAD_GLOBAL 0 (a)
3 LOAD_ATTR 1 (pop)
6 LOAD_GLOBAL 2 (index)
9 CALL_FUNCTION 1
12 POP_TOP
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
The slice and add method.
切片和添加方法。
The least efficient.
最有效的。
Code:
代码:
def slice_method():
global a
global index
a = a[:index] + a[index+1:]
Disassembly:
拆卸:
24 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 SLICE+2
7 LOAD_GLOBAL 0 (a)
10 LOAD_GLOBAL 1 (index)
13 LOAD_CONST 1 (1)
16 BINARY_ADD
17 SLICE+1
18 BINARY_ADD
19 STORE_GLOBAL 0 (a)
22 LOAD_CONST 0 (None)
25 RETURN_VALUE
None
Note: In all three disassembles ignore the last two lines which basically are return None
. Also the first two lines are loading the global values a
and index
.
注意:在这三种反汇编语言中,都忽略了最后两行,它们基本上是返回None。前两行还装载全局值a和索引。
#4
41
pop
is also useful to remove and keep an item from a list. Where del
actually trashes the item.
pop从列表中删除并保留一个条目也很有用。德尔实际上是在破坏物品。
>>> x = [1, 2, 3, 4]
>>> p = x.pop(1)
>>> p
2
#5
12
Generally, I am using the following method:
我一般采用以下方法:
>>> myList = [10,20,30,40,50]
>>> rmovIndxNo = 3
>>> del myList[rmovIndxNo]
>>> myList
[10, 20, 30, 50]
#6
9
This depends on what you want to do.
这取决于你想做什么。
If you want to return the element you removed, use pop()
:
如果要返回删除的元素,请使用pop():
>>> l = [1, 2, 3, 4, 5]
>>> l.pop(2)
3
>>> l
[1, 2, 4, 5]
However, if you just want to delete an element, use del
:
但是,如果您只想删除一个元素,请使用del:
>>> l = [1, 2, 3, 4, 5]
>>> del l[2]
>>> l
[1, 2, 4, 5]
Additionally, del
allows you to use slices (e.g. del[2:]
).
此外,del允许您使用切片(例如del[2:])。
#7
6
Yet another way to remove an element(s) from a list by index.
另一种从列表中按索引删除元素的方法。
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# remove the element at index 3
a[3:4] = []
# a is now [0, 1, 2, 4, 5, 6, 7, 8, 9]
# remove the elements from index 3 to index 6
a[3:7] = []
# a is now [0, 1, 2, 7, 8, 9]
a[x:y] points to the elements from index x
to y-1
. When we declare that portion of the list as an empty list ([]
), those elements are removed.
a[x:y]指向从索引x到y-1的元素。当我们将列表的那一部分声明为空列表([])时,这些元素将被删除。
#8
5
Use the following code to remove element from the list:
使用以下代码从列表中删除元素:
list = [1, 2, 3, 4]
list.remove(1)
print(list)
output = [2, 3, 4]
If you want to remove index element data from the list use:
如果要从列表中删除索引元素数据,请使用:
list = [1, 2, 3, 4]
list.remove(list[2])
print(list)
output : [1, 2, 4]
#9
5
You could just search for the item you want to delete. It is really simple. Example:
你可以搜索你想删除的条目。这是很简单的。例子:
letters = ["a", "b", "c", "d", "e"]
letters.remove(letters[1])
print(*letters) # Used with a * to make it unpack you don't have to (Python 3.x or newer)
Output: a c d e
输出:cde
#10
3
As previously mentioned, best practice is del(); or pop() if you need to know the value.
如前所述,最佳实践是del();或者pop()如果你需要知道它的值。
An alternate solution is to re-stack only those elements you want:
另一种解决方案是只重新堆叠你想要的元素:
a = ['a', 'b', 'c', 'd']
def remove_element(list_,index_):
clipboard = []
for i in range(len(list_)):
if i is not index_:
clipboard.append(list_[i])
return clipboard
print(remove_element(a,2))
>> ['a', 'b', 'd']
eta: hmm... will not work on negative index values, will ponder and update
埃塔:嗯……不会对负面的索引值工作,会思考和更新吗?
I suppose
我想
if index_<0:index_=len(list_)+index_
would patch it... but suddenly this idea seems very brittle. Interesting thought experiment though. Seems there should be a 'proper' way to do this with append() / list comprehension.
将补丁……但突然之间,这个想法显得非常脆弱。有趣的思想实验。似乎应该有一种“合适”的方法来使用append() /列表理解。
pondering
思考
#11
3
It doesn't sound like you're working with a list of lists, so I'll keep this short. You want to use pop since it will remove elements not elements that are lists, you should use del for that. To call the last element in python it's "-1"
这听起来不像是你在处理一份清单,所以我将保持这个简短。您希望使用pop,因为它将删除元素而不是列表元素,您应该使用del。要调用python中的最后一个元素,它是"-1"
>>> test = ['item1', 'item2']
>>> test.pop(-1)
'item2'
>>> test
['item1']
#12
3
Use the "del" function:
使用“▽”功能:
del listName[-N]
For example, if you want to remove the last 3 items, your code should be:
例如,如果您想删除最后3项,您的代码应该是:
del listName[-3:]
For example, if you want to remove the last 8 items, your code should be:
例如,如果您想删除最后8项,您的代码应该是:
del listName[-8:]
#13
1
l - list of values; we have to remove indexes from inds2rem list.
l -值列表;我们必须删除inds2rem列表中的索引。
l = range(20)
inds2rem = [2,5,1,7]
map(lambda x: l.pop(x), sorted(inds2rem, key = lambda x:-x))
>>> l
[0, 3, 4, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
#14
0
You can use either del or pop to remove element from list based on index. Pop will print member it is removing from list, while list delete that member without printing it.
您可以使用del或pop从基于索引的列表中删除元素。Pop将打印它正在从列表中删除的成员,而list删除该成员而不打印它。
>>> a=[1,2,3,4,5]
>>> del a[1]
>>> a
[1, 3, 4, 5]
>>> a.pop(1)
3
>>> a
[1, 4, 5]
>>>
#15
0
One can either use del or pop, but I prefer del, since you can specify index and slices, giving the user more control over the data.
可以使用del或pop,但我更喜欢del,因为您可以指定索引和片,从而使用户能够对数据进行更多的控制。
For example, starting with the list shown, one can remove its last element with del
as a slice, and then one can remove the last element from the result using pop
.
例如,从显示的列表开始,可以使用del作为一个切片来删除它的最后一个元素,然后可以使用pop从结果中删除最后一个元素。
>>> l = [1,2,3,4,5]
>>> del l[-1:]
>>> l
[1, 2, 3, 4]
>>> l.pop(-1)
4
>>> l
[1, 2, 3]
#16
-1
You can simply use the remove
function of Python. Like this:
您可以简单地使用Python的删除函数。是这样的:
v = [1, 2, 3, 4, 5, 6]
v.remove(v[4]) # I'm removing the number with index 4 of my array
print(v) # If you want verify the process
# It gave me this:
#[1,2,3,4,6]