Outcast
Outcast

Reputation: 5117

Remove element from list and print new list in the same statement

I am using the .remove() function to remove an element from a list and then I want to use directly this new list into another function e.g. the print() function. When I am doing this then I get the following:

print([1, 2, 3])
# [1, 2, 3]

print([1, 2, 3].remove(2))
# None

So if I want to use directly another function (e.g. print()) after an Inplace function such as .remove()then paradoxically I can only do this like this:

print([1, 2, 3])
# [1, 2, 3]

x = [1, 2, 3]
x.remove(2)
print(x)
# [1, 3]

Is there any better way to do this instead of writing this additional source code?

Apparently the same problem applies for all Inplace functions as attributes of other functions I guess.

Upvotes: -2

Views: 1634

Answers (4)

2diabolos.com
2diabolos.com

Reputation: 1011

There is a slightly better way (even if I also think it is not better than using remove() )

print([v for v in l if v != 2]) 

Upvotes: 0

tevemadar
tevemadar

Reputation: 13225

You can wrap it into a one-liner using a lambda, if you really want to:

print( (lambda x,y:x if x.remove(y) is None else None) ([1, 2, 3], 2) )

Do you need a copy of the Disclaimer from the other two answers? In short: it is not a very readable piece of code.

Upvotes: 0

user24343
user24343

Reputation: 912

If you really want one statement without modifying the list in question, you could try my_list[:my_list.index(value)]+my_list[my_list.index(value)+1:]. This has the drawbacks

  • you calculate my_list.index(value) twice (will not be neccessary 3.8+, see PEP572)
  • you slice and add, which is much more than just removing
  • it isn't really (near) as clear as my_list.remove(val)

And,


Disclaimer: I really don't recommend you to do this. But, this is just a method that came to my mind.

I really don't see a problem in writing list.remove() and print in separate statements.

--Jay

Upvotes: 0

Jay
Jay

Reputation: 24905

You can create a wrapper function for list remove and call that function instead of calling list.remove directly.

def list_remove(l, elem):
    l.remove(elem)
    return l

print (list_remove(l, elem))

Disclaimer: I really don't recommend you to do this. But, this is just a method that came to my mind.

I really don't see a problem in writing list.remove() and print in separate statements.

Upvotes: 0

Related Questions