How to specify a position in the list and use it?

Is there a way so that I can specify a position in the list, for example. 2 for the third value, and then directly use this position, for example list.remove [2]?

For example:

Say my list was,

test = [0,1,2,3,2,2,3]

Is there a way for the user to want to remove the fifth value, which is environment 2, then you can just give the position and use it directly. In this case, if I used test.remove (2), it would delete the first 2 that appeared in the list, so there is a way I could say in middle position 2, and then delete it without touching the rest list?

Something like test.remove[2]would be a good idea for implementation, the value in [] would be a position.

+4
source share
3 answers

You can use list.pop:

>>> test = [0,1,2,3,2,2,3]
>>> test.pop(5)            #Removes the item and returns it as well
2
>>> test
[0, 1, 2, 3, 2, 3]

or del:

>>> test = [0,1,2,3,2,2,3]
>>> del test[5]           #Only removes the item
>>> test
[0, 1, 2, 3, 2, 3]
+2
source

Sometime at the beginning of my use of this resource, someone suggested that I learn how to use the Python introspection ability, as this often helps answer my questions. In your case

test =  [0,1,2,3,2,2,3]

To learn about the methods that I can perform,

dir(test)

results

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Ignoring elements that begin with underscores and use some language skills, I want to understand if pop or delete helps me in order to

help(test.pop)

Help on built-in function pop:

pop(...)
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.

Please note that this is not a criticism of your question, but I hope this helps you understand that Python has some tools that will help you understand functions very efficiently.

+2
source

remove . , ; .

, find , , , :

value = test[2]

, replace , :

test[2] = new_value

, remove , :

del test[2]

"" del", , , .

+2

Source: https://habr.com/ru/post/1527418/


All Articles