Python List append() Method with Examples - Scaler Topics (original) (raw)

Overview

The append() function in Python helps us add an element at the end of the list. It doesn't create a new list but modifies the existing one.

Syntax of append() Function in Python

The append function in Python has the following syntax:

The myList is the list where we want to add the element.

Parameters of append() Function in Python

It accepts a single element which could be any Python object

This parameter is mandatory and can't be omitted. Leaving this parameter empty will give an error.

Return Value of append() Function in Python

Return Type: None

The append function doesn't return anything. It only modifies the original list.

Example of append() Function in Python

Here we will add elements like integers, floating numbers, and a string to a list.

Output

Explanation

What is append() Function in Python?

For example, if you have a list of overall toppers of the school, this list will always need to be updated every year to add new toppers at the end of the list. Ever wondered how you would update the list most easily? The answer to this problem is the Python append function, which adds an element at the end of the list.

The append() function of Python is used to add an item at the end of the list to which it is applied. The append function takes an element as a parameter to be added to the list.

The append function doesn't create a new list after adding the item, but it modifies the original list, i.e., it updates the same list by adding the item at its end.

Time Complexity for Append in Python

This function has constant time complexity i.e. O(1), because lists are randomly accessed so the last element can be reached in O(1) time that's why the time taken to add the new element at the end of the list is O(1).

Also, when a list is created in Python, it reserves 32 bits of the contiguous memory location. Whenever the combined size of elements of that list exceeds the memory space of the original list, it acquires the contiguous memory at another location of size double its previous size. In that scenario, the previous elements are copied to this new memory space, and new elements are appended to the list. So, this is considered as the worst case for appending any element to the list and the time complexity for this worst case is O(N) where N is the size of the original list.

More Examples

Example 1: Adding iterables to the existing list

Here, we will add iterables like lists, sets, or a dictionary to an existing list.

Output

Explanation

Example 2: Nested Lists

Here we are going to append a list2 into a list1 and then another list3 into the list2, let's see what will happen.

Output:

Explanation

Click Here, to know more about nested lists in Python.

Conclusion