简体   繁体   中英

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

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("row")
r = rvals.remove("row")
print(r)

but it turns out this doesnt really work and it gives ra NoneType value instead of removing what i wanted and storing it. Is there a way to do this?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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