Account
Categories

Python extend() Method


Definition:

If you need to add multiple values to a list, this method adds them to the list. It adds all the values from another list to the end of the list.

Note: This method takes an iterable and adds each element to the list.

Now you will clearly understand the method through the flowchart .


List A →  a = [10, 20]

List B (Source) →  b = [30, 40]
                         ↓        ↓
                      (values to add)

Method →  a.extend(b)

Flow →      30  ─────►
            40  ─────►   (added to A)

After Extend →  [10, 20, 30, 40]

Index :    0      1      2      3  
           ↓      ↓      ↓      ↓
Value :   10     20     30     40

Syntax

list_name.extend(iterable)

Example:

a = [10, 20]
b = [30, 40]
a.extend(b)
print(a)

Output:

Exercise

Add values from list b = [5, 6] to list a = [1, 2, 3] using Python.