Web Development Course:
TL;DR – The Python append method allows you to add an extra item at the end of a specified list.
The append function in Python
Lists are among the most commonly used data types in Python. They contain multiple elements: strings, numbers, dictionaries, etc. To add an extra element at the end of the list, we use the Python
xList = ['yellow', 'red', 'blue']; xList.append('green');
You can even append Python lists with other lists:
xList = ['yellow', 'red', 'blue']; yList = ['1', '2', '3'] xList.append(yList);
The syntax for append in Python
Using the Python
append method is simple – all you need to define is the list and the element to add:
append function in Python doesn't have a return value: it doesn't create any new, original lists. Instead, it updates a list that already exists, increasing its length by one.
Python append: useful tips
- To add elements of a list to another list, use the
extendmethod. This way, the length of the list will increase by the number of elements added.
- To add an element to a specified location and not the end of the list, use the
insertmethod. It takes two arguments: the index of the element it will be inserted after, and the new element to insert.