1

I am trying to use list comprehension for a Numpy array and then append another element after. Then I noticed something strange.

a = [i for i in machine]
a.append("All")
print(a)

This returns [251, 360, 661, 662, 852, 'All']

While

a = [i for i in machine].append("All")

Returns None

Why does this returns a None object? Is there a way to do this in one line?

tonywang
  • 181
  • 2
  • 13

1 Answers1

5

append changes the list you call it on. It doesn’t produce a new list, so it returns None to avoid confusion.

Python 3.6+, using a splat (expands an iterable) in a list literal:

a = [*machine, "All"]

previously, list concatenation with the + operator:

a = list(machine) + ["All"]
Ry-
  • 218,210
  • 55
  • 464
  • 476