Home > Back-end >  Removing an item and printing the list in one line
Removing an item and printing the list in one line

Time:12-11

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.

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

the difference is that you print functions once and print variables once:

alist = ["a","b","c"]
print(alist.remove('b')) # function return None
print(alist) # printing result 

CodePudding user response:

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)

  • Related