How to Append & Extend Element to Python List

Published on October 4, 2020 38 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

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. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *