programing

목록에서 del, remove 및 pop의 차이점

nasanasas 2020. 9. 29. 07:52
반응형

목록에서 del, remove 및 pop의 차이점


>>> a=[1,2,3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a=[1,2,3]
>>> del a[1]
>>> a
[1, 3]
>>> a= [1,2,3]
>>> a.pop(1)
2
>>> a
[1, 3]
>>> 

목록에서 요소를 제거하는 위의 세 가지 방법간에 차이점이 있습니까?


예, 특정 색인이 아닌 첫 번째 일치 값을remove 제거합니다 .

>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]

del 특정 색인에서 항목을 제거합니다.

>>> a = [3, 2, 2, 1]
>>> del a[1]
>>> a
[3, 2, 1]

pop특정 지수 및 반품이있는 항목을 제거합니다.

>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]

오류 모드도 다릅니다.

>>> a = [4, 5, 6]
>>> a.remove(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> del a[7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a.pop(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range

사용 del, 인덱스로 요소를 제거하기 위해 pop()반환 된 값을 필요로하는 경우 인덱스를 제거하고, remove()값으로 요소를 삭제합니다. 후자는 목록을 검색해야하며 목록에 ValueError그러한 값이 없으면 발생합니다.

요소 i목록에서 색인 삭제할 때 n이러한 방법의 계산 복잡성은 다음과 같습니다.

del     O(n - i)
pop     O(n - i)
remove  O(n)

다른 누구도 언급하지 않았으므로 del(와 달리 pop) 목록 분할로 인해 인덱스 범위를 제거 할 수 있습니다.

>>> lst = [3, 2, 2, 1]
>>> del lst[1:]
>>> lst
[3]

또한 IndexError인덱스가 목록에없는 경우를 방지 할 수 있습니다 .

>>> lst = [3, 2, 2, 1]
>>> del lst[10:]
>>> lst
[3, 2, 2, 1]

이미 다른 사람들이 꽤 잘 대답했습니다. 이것은 내 끝에서 :)

제거 대 팝 대 델

분명히, pop값을 반환하는 remove유일한 사람이고 객체를 검색하는 유일한 사람이며 del단순한 삭제로 제한됩니다.


pop-인덱스를 취하고 값을 반환합니다.

remove-값을 취하고 첫 번째 항목을 제거하고 아무것도 반환하지 않습니다.

delete-인덱스를 가져 와서 해당 인덱스에서 값을 제거하고 아무것도 반환하지 않습니다.


여기에 가장 좋은 설명이 많이 있지만 더 단순화하기 위해 최선을 다할 것입니다.

Among all these methods, reverse & pop are postfix while delete is prefix.

remove(): It used to remove first occurrence of element

remove(i) => first occurrence of i value

>>> a = [0, 2, 3, 2, 1, 4, 6, 5, 7]
>>> a.remove(2)   # where i = 2
>>> a
[0, 3, 2, 1, 4, 6, 5, 7]

pop(): It used to remove element if:

unspecified

pop() => from end of list

>>>a.pop()
>>>a
[0, 3, 2, 1, 4, 6, 5]

specified

pop(index) => of index

>>>a.pop(2)
>>>a
[0, 3, 1, 4, 6, 5]

WARNING: Dangerous Method Ahead

delete(): Its a prefix method.

Keep an eye on two different syntax for same method: [] and (). It possesses power to:

1.Delete index

del a[index] => used to delete index and its associated value just like pop.

>>>del a[1]
>>>a
[0, 1, 4, 6, 5]

2.Delete values in range [index 1:index N]

del a[0:3] => multiple values in range

>>>del a[0:3]
>>>a
[6, 5]

3.Last but not list, to delete whole list in one shot

del (a) => as said above.

>>>del (a)
>>>a

Hope this clarifies the confusion if any.


Any operation/function on different data structures is defined for particular actions. Here in your case i.e. removing an element, delete, Pop and remove. (If you consider sets, Add another operation - discard) Other confusing case is while adding. Insert/Append. For Demonstration, Let us Implement deque. deque is a hybrid linear data structure, where you can add elements / remove elements from both ends.(Rear and front Ends)

class Deque(object):

  def __init__(self):

    self.items=[]

  def addFront(self,item):

    return self.items.insert(0,item)
  def addRear(self,item):

    return self.items.append(item)
  def deleteFront(self):

    return self.items.pop(0)
  def deleteRear(self):
    return self.items.pop()
  def returnAll(self):

    return self.items[:]

In here, see the operations:

def deleteFront(self):

    return self.items.pop(0)
def deleteRear(self):
    return self.items.pop()

Operations have to return something. So, pop - With and without an index. If I don't want to return the value: del self.items[0]

Delete by value not Index:

  • remove :

    list_ez=[1,2,3,4,5,6,7,8]
    for i in list_ez:
        if i%2==0:
            list_ez.remove(i)
    print list_ez
    

Returns [1,3,5,7]

let us consider the case of sets.

set_ez=set_ez=set(range(10))

set_ez.remove(11)

# Gives Key Value Error. 
##KeyError: 11

set_ez.discard(11)

# Does Not return any errors.

While pop and delete both take indices to remove an element as stated in above comments. A key difference is the time complexity for them. The time complexity for pop() with no index is O(1) but is not the same case for deletion of last element.

If your use case is always to delete the last element, it's always preferable to use pop() over delete(). For more explanation on time complexities, you can refer to https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt


The remove operation on a list is given a value to remove. It searches the list to find an item with that value and deletes the first matching item it finds. It is an error if there is no matching item, raises a ValueError.

>>> x = [1, 0, 0, 0, 3, 4, 5]
>>> x.remove(4)
>>> x
[1, 0, 0, 0, 3, 5]
>>> del x[7]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[7]
IndexError: list assignment index out of range

The del statement can be used to delete an entire list. If you have a specific list item as your argument to del (e.g. listname[7] to specifically reference the 8th item in the list), it'll just delete that item. It is even possible to delete a "slice" from a list. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3, 4]
>>> del x[3]
>>> x
[1, 2, 3]
>>> del x[4]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[4]
IndexError: list assignment index out of range

The usual use of pop is to delete the last item from a list as you use the list as a stack. Unlike del, pop returns the value that it popped off the list. You can optionally give an index value to pop and pop from other than the end of the list (e.g listname.pop(0) will delete the first item from the list and return that first item as its result). You can use this to make the list behave like a queue, but there are library routines available that can provide queue operations with better performance than pop(0) does. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3] 
>>> x.pop(2) 
3 
>>> x 
[1, 2]
>>> x.pop(4)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x.pop(4)
IndexError: pop index out of range

See collections.deque for more details.


You can also use remove to remove a value by index as well.

n = [1, 3, 5]

n.remove(n[1])

n would then refer to [1, 5]

참고 URL : https://stackoverflow.com/questions/11520492/difference-between-del-remove-and-pop-on-lists

반응형