Insert an item at end of a Python list
This post will discuss how to insert an item at the end of a list in Python.
1. Using list.append(x) function
You can add new items at the end of the list by using the append() function:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': l = ['A', 'B', 'C'] x = 'D' l.append(x) print(l) # prints ['A', 'B', 'C', 'D'] |
2. Using list.insert(i, x) function
You can also use the list’s insert() function that inserts an item at the specified position.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': l = ['A', 'B', 'C'] x = 'D' l.insert(len(l), x) print(l) # prints ['A', 'B', 'C', 'D'] |
3. Using Iterable Unpacking Operator
Another plausible way of insertion at the end is using the * iterable unpacking operator. This feature was introduced with Python 3.5 by the acceptance of PEP 448 – Additional Unpacking Generalizations.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': l = ['A', 'B', 'C'] x = 'D' l = [*l, x] print(l) # prints ['A', 'B', 'C', 'D'] |
4. Creating a new list
Another approach is to convert the given item into a list first and then concatenate it to the existing list. Note that this solution is slower than all the above solutions since it creates a new list.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': l = ['A', 'B', 'C'] x = 'D' l += [x] # or use slicing: l[len(l):] = [x] print(l) # prints ['A', 'B', 'C', 'D'] |
That’s all about inserting an item at the end of a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)