Ton Le
Ton Le

Reputation: 25

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 r a NoneType value instead of removing what i wanted and storing it. Is there a way to do this?

Upvotes: 2

Views: 9314

Answers (2)

Khushi Makhecha
Khushi Makhecha

Reputation: 1

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.

Upvotes: 0

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

Upvotes: 3

Related Questions