Python list append – How to add elements to list in Python

Python list append method

The append method of Python adds or appends an element to the existing list.

Syntax of append method

List_name.append(object/element)

Where object/element is the one to be appended to the list.

Examples of using append method

Below example shows how to add single element by using append method

Output will be:

List before append: [‘this’, ‘is’, ‘list’, ‘chapter’]

List after append: [‘this’, ‘is’, ‘list’, ‘chapter’, ‘explaining append method’]

Python extend method

Python extend method also appends given to existing list. Difference between extend and append can be seen in example below. Inspite of an element, another list can also appended to existing list.

Syntax of extend

List_name.extend(elements or list)

Example of using extend

Output will be:

List before extend: [‘this’, ‘is’, ‘list’, ‘chapter’]

List after extend method: [‘this’, ‘is’, ‘list’, ‘chapter’, ‘explaining extend method’, ‘ with multiple elements!’

From output you can see the one of the difference between append and extend: Extend added elements separately in existing list whereas in case of append whole string in appended was taken as single element.

In extend if you enclose a string in quotes without square brackets and extend an existing list, each character will be treated as separate element of extended list. For example:

List before extend: [‘a’, ‘b’, ‘c’]

List after extend method: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

If we display length of above example for both extend and append, the code and output will be as follows:

Output will be:

List before append: [‘a’, ‘b’, ‘c’]

length before append =  3

List after append: [‘a’, ‘b’, ‘c’, ‘def’]

length after append =  4

##########################################

List before extend: [‘a’, ‘b’, ‘c’]

length before extend =  3

List after extend: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

length after extend =  6


Was this article helpful?

Related Articles

Leave A Comment?