简体   繁体   English

通过弹出删除最后一个列表元素

[英]Removing last list element by popping

I have the following piece of Python code where I am trying to empty out list A by removing one element at a time starting from the end.我有以下一段 Python 代码,我试图通过从末尾开始一次删除一个元素来清空列表 A。 I cannot seem to reduce the list to an empty one and I would like to know why not.我似乎无法将列表缩减为空列表,我想知道为什么不这样做。 Any insight would be extremely appreciated.任何见解将不胜感激。

A = [3,4,5,6,2]
for i in A:
    A.pop()
var = [3,4,5,6,2]
for x in range(len(var)):
    a = var.pop(-1)
    print(a)

or reverse a list或反转列表

var = var[::-1]

You can try this:你可以试试这个:

A = [3,4,5,6,2]

for a in range(len(A)):
    A.pop(-1)

Output:输出:

>>> A
[]

You can also use a list comprehension instead of a traditional for loop:您还可以使用list comprehension代替传统的for循环:

A = [3,4,5,6,2]
[A.pop(-1) for a in range(len(A))]

Output:输出:

>>> A
[]

Here you are trying to iterate through the elements of a list while the length of the list is reduced by 1 for each iteration.在这里,您尝试遍历列表的元素,而每次迭代列表的长度都会减少 1。

This is not the right way to do this,这不是正确的做法,

Try this,尝试这个,

A = [3,4,5,6,2]
for _ in range(len(A)):
    A.pop()

This will work.这将起作用。

Note: Never loop through a list in which you are going to perform some operations inside the loop-body.注意:切勿循环遍历您将在循环体内执行某些操作的列表。 Try duplicating the list or use some other conditions.尝试复制列表或使用其他一些条件。

This issue you are facing because you are trying to iterate the loop from first element and trying to remove the last element of the list.您面临的这个问题是因为您试图从第一个元素迭代循环并尝试删除列表的最后一个元素。 at one pint for loop runs out of element in a list hence it stops and you don't get empty list.一品脱 for 循环用完列表中的元素,因此它停止并且您不会得到空列表。

The proper solution will be to reverse iterate through the list and remove the elements.正确的解决方案是反向迭代列表并删除元素。

Sample Code :示例代码:

A = [3,4,5,6,2]
for i in range( len(A) -1 , -1, -1):
        A.pop()
        print (A)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM