How do i remove an item from a list and store it into a variable in python

后端 未结 2 1573
半阙折子戏
半阙折子戏 2020-12-21 11:46

so i want to remove an item from a list and store it into the variable at the same time in python. I tried a sample code like this:

rvals = []
rvals.append(\         


        
相关标签:
2条回答
  • 2020-12-21 11:55

    list.remove(x)

    Remove the first item from the list whose value is x. It is an error if there is no such item.

    So, as stated in the docs, you will not get the value returned.

    This can help:

    value = "row"
    
    rvals = []
    rvals.append(value)
    print rvals.pop(rvals.index(value))
    

    Or just use pop(), if you only want to remove and get the last inserted item:

    value = "row"
    
    rvals = []
    rvals.append(value)
    print rvals.pop()
    

    Output:

    row
    
    0 讨论(0)
  • 2020-12-21 12:05

    Printing a removed element from the list using remove() method generally results in None. Hence, a better approach is to, first store the element to be removed and then remove it from the list.

    0 讨论(0)
提交回复
热议问题