How to Append & Extend Element to Python List

In this article, I’m going to show how to add element o python list. Let’s see:

Table of Contents

  1. Append Element
  2. Append List
  3. Append Dictionary
  4. Append vs Extend

Append Element

The append() method adds an element to the end of the list.

list_capital = ['Dhaka', 'London']

list_capital.append('Tokyo')

print("Updated List : ", list_capital)

Append List

list = [[1, 2, 3], [4, 5, 6]]

list.append([7, 8, 9])

print("Updated List : ", list)

Append Dictionary

Similarly element & list, we can add dictionary:

list = [{"a": 1, "b": 2}]

list.append({"c": 3, "d": 4})

print("Updated List : ", list)

Append vs Extend

If you use append for more than one element, you have to pass a list of elements as arguments and you will obtain a nested list!

list_a = [1,2]
list_a.append([3,4])
print("Append to list a : ", list_a)

Output:

Append to list a :  [1, 2, [3, 4]]

With extend, instead, you pass a list as an argument, but you will obtain a list with the new element that is not nested in the old one.

list_b = [1,2]
list_b.extend([3,4])
print("Extend to list b: ", list_b)

Output:

Extend to list b:  [1, 2, 3, 4]
That’s it. Thanks for reading. ?

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.