Python List append()

Python list‘s append method adds single item to the end of the list.You can add any type of item int, string, list, tuple or dictionary to the list using list’s append method.It does not return anything but modifies original list.


Syntax

Here l is object of the list.


Return

returns nothing, it just make changes to original list.


Example

Let’s see a very simple example:

l=[1,2,3,4] l.append(5) print(l) #You can append any object to the list l.append("six") print(l)

Output:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, ‘six’]

Let’s add another list to existing list using append method

l1=[1,2,3,4] l2=[5,6,7,8] l1.append(l2) print(l1)

Output:

[1, 2, 3, 4, [5, 6, 7, 8]]

Please note that second list is appended as it is to l1.
Let’s get element 6 from list l1. As list item 6 belongs to inner list in list l1, we have to access it as below.

Let’s add tuple to the list.

l1=[1,2,3] t=(5,6,7) l1.append(t) print(l1) print(l1[3][2])

Output:

[1, 2, 3, (5, 6, 7)]
7

That’s all about Python List append().

Leave a Reply

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