0

This is my code:

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

Output:

[1, 2, 3]
None

Why was None printed instead of [1, 2, 3, 1]?

I used to try some stuff with pandas DataFrames and I remember a parameter named inplace.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(12).reshape(3, 4),
                  columns=['A', 'B', 'C', 'D'])
print(df)

print(df.drop(['B', 'C'], axis=1))

df1 = df.drop(['B', 'C'], axis=1)

print(df)
print(df1)

Output:

   A  B   C   D
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
   A   D
0  0   3
1  4   7
2  8  11
   A  B   C   D
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
   A   D
0  0   3
1  4   7
2  8  11

It has been said in this answer that it's harmful to use inplace=True. So, I got habituated to assigning the new dataframe to a new variable (or re-assigning to same variable). So, I thought that lists work similar to pandas DataFrame w.r.t. inplace concept... but I don't think that's the case after reading my output for a.append(). Can you please explain about this in detail?

Random Person
  • 163
  • 1
  • 17
  • 3
    `list.apppend` changes the list in place and returns nothing, so your statement deletes the original list. It essentially acts just like `inplace=True` in pandas. – Tim Roberts Dec 20 '22 at 17:31
  • If your really want to create a new list each time you append, then `a = a + [b]` will append `b` to `a` and create a new list. But this isn't typical Python – Frank Yellin Dec 20 '22 at 17:34
  • @FrankYellin why isn't that typical Python? You mean .extend() is a better way of doing it? – Random Person Dec 20 '22 at 17:37
  • 1
    .extend does the same thing. Modifies in place and returns None. It just adds multiple elements rather than a single element. Most Python code just uses `append` or `extend`, to modify lists, and then copies the list as necessary. – Frank Yellin Dec 20 '22 at 17:48

1 Answers1

1

The list.append() method adds an element to the end of a list, but it does not return a new list with the element added. Instead, it returns None. This is why None is printed instead of the modified list.

To print the modified list, you can simply print the list again after calling append():

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

Output:

[1, 2, 3]
[1, 2, 3, 1]
Ludo Schmidt
  • 1,283
  • 11
  • 16
  • Found this in the [docs](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists): "*You might have noticed that methods like `insert`, `remove` or `sort` that only modify the list have no return value printed – they return the default `None`*." – Random Person Dec 20 '22 at 17:40