1

So as the question says, is it possible to remove an element and return the list in one line?

So if lets say

a = [1, 3, 2, 4]
b = a.remove(1)

This would set b to be NoneType, so I was wondering if there's a way to do this.

TheAmateurProgrammer
  • 9,252
  • 8
  • 52
  • 71

4 Answers4

3

I suppose this would work:

a = [1, 3, 2, 4]
b = (a.remove(1), a)[1]

This is assuming that you want to do both things:

  1. Modify the original list by removing the element, and
  2. Return the (now modified) list.

EDIT

Another alternative:

b = a.remove(1) or a

Both are fairly confusing; I'm not sure I would use either in code.

EDIT 2

Since you mentioned wanting to use this in a lambda... are you aware that you can use an actual named function any time you would otherwise use a lambda?

E.g. instead of something like this:

map(lambda x: x.remove(1) and x, foo)

You can do this:

def remove_and_return(x):
    x.remove(1)
    return x

map(remove_and_return, foo)
user94559
  • 59,196
  • 6
  • 103
  • 103
2

Since remove returns None, you could just or a to it:

>>> a = [1, 3, 2, 4]
>>> a.remove(1) or a
[3, 2, 4]
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
0

List a assign to b:

b = a.remove(1) or a  
a is b     # True

Using b is the same to use a, and it's dangerous if you get a final object like [b, c, d], because if you update one of this list element, the all elements will update too.

Compare to:

import copy
b = a.remove(1) or copy.copy(a)

I think this way should be safer.

Joey.Chang
  • 164
  • 2
  • 14
0

pure functional solution that does not touch passed list

>>> a = [1,2,3]
>>> (lambda a,b: (lambda a0,a1: (a0.remove(b),a1)[-1] )( *((a.copy(),)*2) ))(a, 3)
[1,2]
>>> a
[1,2,3]
iperov
  • 455
  • 7
  • 8