Python List – extend()

Python list.extend(iterable) method appends all the elements from the iterable to this list.

extend() method modifies the original list.

Syntax

The syntax to call extend() method on a list myList is

</>
Copy
myList.extend(iterable)

where

  • myList is a Python list
  • extend is method name
  • iterable is any Python iterable like list, set, tuple, string, etc.

Examples

Extend List with Elements from another List

In the following program, we initialize a list myList with some elements. We shall take another list anotherList as well initialized with some elements. We append myList with the elements from anotherList using extend() method.

main.py

</>
Copy
#take a list
myList = ['apple', 'banana', 'cherry']

#another list
anotherList = ['mango', 'grape']

#append elements in anotherList to myList
myList.extend(anotherList)

print(f'myList : {myList}')

Output

myList : ['apple', 'banana', 'cherry', 'mango', 'grape']

Extend List with Elements from Tuple

In the following program, we initialize a list myList with some elements. We shall take a tuple myTuple initialized with some elements. We append myList with the elements from myTuple using extend() method.

main.py

</>
Copy
#take a list
myList = ['apple', 'banana', 'cherry']

#take a tuple
myTuple = [41, 85]

#append elements in myTuple to myList
myList.extend(myTuple)

print(f'myList : {myList}')

Output

myList : ['apple', 'banana', 'cherry', 41, 85]

Conclusion

In this Python Tutorial, we learned how to append a list with the elements from an iterable like a list, tuple, set, etc., using list.extend() method.