Python List Append - And what's the difference of the append and extend?

You can append an object to the list using append method.

a = [5, 6, 7]
a.append(8)

print(a)  # [5, 6, 7, 8]

The append() takes one argument.

a = [5, 6, 7]
a.append(8, 9)

# TypeError: append() takes exactly one argument (2 given)

Equivalent expression

a = [1, 2]
a[len(a):] = [5]

print(a)  # [1, 2, 5]

The insert() is similar to the append().

a = [1, 2]
a.insert(len(a), 7)

print(a)  # [1, 2, 7]

Addition of Python lists

If you want to append several items, substitute + (addition operator) with append().

a = [1, 2]
b = [3, 4, 5]

c = a + b

print(c)  # [1, 2, 3, 4, 5]

A list plus an empty list:

a = ['apple', 'lemon']
b = []

c = a + b

print(c)  # ['apple', 'lemon']

Append and extend

a = [1, 2]
b = [1, 2]

x = [3, 4]

a.append(x)
b.extend(x)

print(a)  # [1, 2, [3, 4]]
print(b)  # [1, 2, 3, 4]

The extend() appends all the elements of the argument to the list, while the append() simply appends the argument to the list.

What does the append() return?

a = [1, 2]

b = a.append(3)

print(b)  # None

The append() returns None.

Append None to the list

a = [1, 2]

a.append(None)

print(a)  # [1, 2, None]

The object id doesn't change by appending

a = [1, 2]
print(id(a))  # 4524080000

a.append(3)
print(id(a))  # 4524080000

The id() is an important built-in function in Python and returns the identity of an object. The value, instance, function, class are all objects in Python. To check the difference of above and below codes helps us to understand the Python assignment.

a = [1, 2]
print(id(a))  # 4423605376

a = [1, 2, 3]
print(id(a))  # 4423606144

Note: What happens when you append the list to itself?

a = [1, 2]

a.append(a)

print(a)  # [1, 2, [...]]
print(a[2])  # [1, 2, [...]]
print(a[2][2])  # [1, 2, [...]]
print(len(a))  # 3

It's nonsense but raises no exception. The code is valid in Python.

Python List

Python Tutorial