-1

I was looking for a one-line way to remove an item from a list and then print the list. The first bit of code works and is straight forward and does what I want:

alist = ["a", "b", "c"]
alist.remove("b")
print(alist)

Which produces the result we want: ["a", "c"]

But when I tried to make it one line:

print(["a","b","c"].remove("b"))

It returns None. Can someone explain the difference between these? I have seen this question but it does not explain why these produce different outputs, and does not really make it all work in one line.

And this is not actually important for anything, I am just trying to learn what is going on here. Thanks.

N. Owad
  • 103
  • 5
  • 3
    [`remove`](https://docs.python.org/3/tutorial/datastructures.html) modifies the list in-place, it returns `None`. – Maroun Dec 10 '21 at 14:47
  • Does this answer your question? [remove() returns None when I try to remove a variable from a list](https://stackoverflow.com/questions/45046415/remove-returns-none-when-i-try-to-remove-a-variable-from-a-list) – nikeros Dec 10 '21 at 14:50

3 Answers3

0

This happens because the remove function works in place. An in-place function doesn't have a return value (which is why you get None) and in print(["a","b","c"].remove("b")) you are effectively trying to send the return value of the in place remove function to the print function.

As you correctly stated,

alist = ["a", "b", "c"]
alist.remove("b")
print(alist)

would be the correct use of a in-place function.

0

The method remove acts on the list object upon which it was called. So after alist.remove("b"), the name alist refers to a list ["a", "c"].
However, the method remove does not return the list a. There is no need for the method to return anything (because it does its job in-place, that is on the list alist). Thus the return value is None. (Also see the documentation.)

If you do

print(["a", "b", "c"].remove("b"))

then the return value is printed, i.e. None. If you do

alist = ["a", "b", "c"]
alist.remove("b")
print(alist)

then alist is printed (after it has been modified by remove(). The latter is usually what you want.

Concerning your desire to have this as a one-liner: I would not recommend you to remove a list element and print the resulting list in one line. It usually makes your code quite hard to read. Instead, the code you provided is just fine (it's a two-liner if you don't count the initialization of alist).
But if you are still curious to do this in one line, see this answer. You mentioned the same thread in your question; I think the answer is fine in giving a one line solution.

NerdOnTour
  • 634
  • 4
  • 15
-1

Remove method won't return any value in python it just remove a element from the list.



    print(["a","b","c"].remove("b"))

In the above case remove() just remove "b" value and returns Nothing Thats why it shows "None" as output

You can check it with below code

l=["d","e","f"]
print(l.remove("e"))
print(l)