AlexM
AlexM

Reputation: 1183

Why can't a list be constructed and modified in the same line?

For example, why is a not equal to b?

a = [1]
a.append(2)
print(a)  # [1, 2]

b = [1].append(2)
print(b)  # None

The syntax for b doesn't look wrong to me, but it is. I want to write one-liners to define a list (e.g. using a generator expression) and then append elements, but all I get is None.

Upvotes: 0

Views: 157

Answers (3)

SolomSong
SolomSong

Reputation: 306

All built-in methods under class 'List' in Python are just modifying the list 'in situ'. They only change the original list and return nothing.

The advantage is, you don't need to pass the object to the original variable every time you modify it. Meanwhile, you can't accumulatively call its methods in one line of code such as what is used in Javascript. Because Javascript always turns its objects into DOM, but Python not.

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71580

It's because:

append, extend, sort and more list function are all "in-place".

What does "in-place" mean? it means it modifies the original variable directly, some things you would need:

l = sorted(l)

To modify the list, but append already does that, so:

l.append(3)

Will modify l already, don't need:

l = l.append(3)

If you do:

l = [1].append(2)

Yes it will modify the list of [1], but it would be lost in memory somewhere inaccessible, whereas l will become None as we discovered above.

To make it not "in-place", without using append either do:

l = l + [2]

Or:

l = [*l, 2]

Upvotes: 3

AlexM
AlexM

Reputation: 1183

The one-liner for b does these steps:

  1. Defines a list [1]
  2. Appends 2 to the list in-place
  3. Append has no return, so b = None

The same is true for all list methods that alter the list in-place without a return. These are all None:

c = [1].extend([2])
d = [2, 1].sort()
e = [1].insert(1, 2)
...

If you wanted a one-liner that is similar to your define and extend, you could do

c2 = [1, *[2]]

which you could use to combine two generator expressions.

Upvotes: 2

Related Questions