Python list append: The Complete Guide

Python has a great built-in list type named “list.” List literals are written within square brackets [ ]. Lists work similarly to strings, use the len() function and square brackets [ ] to access data, with the first element at index 0. The append() method in Python appends an element or item to the end of the list. The list append() method 

Python list append

List append() is a built-in Python method that adds a single element to the existing list. The list.append() method takes an element as an argument and doesn’t return a new list; instead, it modifies the original list.

Syntax

The append() method is the following.

list.append(item)

Parameters

The list append() method takes a single element and adds it to the end of the list. An element can be numbers, strings, another list, dictionary, etc.

Adding Element to a List in Python

To add an element to a list in Python, use the list.append() method. Create a file called app.py and add the following code inside it.

// app.py

GoT = ['Daenerys', 'Jon', 'Tyrion']
Friends = 'Rachel'

GoT.append(Friends)
print(GoT)

Save the file and go to the cmd or terminal and run the file using the following command.

python3 app.py

Python List append() Method Example | Python Standard Libary

Adding List to a List in Python

To add a list to the list in Python, use the list.append() function. Write the following code inside the app.py file.

GoT = ['Daenerys', 'Jon', 'Tyrion']
Friends = ['Rachel', 'Monica', 'Phoebe']

GoT.append(Friends)
print(GoT)

In the above example, we are adding a list to the list. So the second list considers a single list item and it appends as a separate item. The output is the following.

Adding List to a List in Python

Again, it does not return a new list, modifies the original.

That’s it for this tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.