TheAmateurProgrammer
TheAmateurProgrammer

Reputation: 9392

To remove an element and assign the list in one line

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.

Upvotes: 1

Views: 1566

Answers (4)

iperov
iperov

Reputation: 524

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]

Upvotes: 0

Joey.Chang
Joey.Chang

Reputation: 164

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.

Upvotes: 0

user94559
user94559

Reputation: 60153

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)

Upvotes: 3

Stefan Pochmann
Stefan Pochmann

Reputation: 28656

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

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

Upvotes: 2

Related Questions