How to Add a Value to the End and Return a New List in Python?

In Python, to add a value to the end and return a new list (as opposed to modifying it in-place), you can do the following:

# Python 3+
existing_list = ['foo', 'bar']
new_list = [*existing_list, 'baz']

print(new_list) # ['foo', 'bar', 'baz']

In the example above, the existing list is unpacked first (using *), and the value you wish to add to the end is added right after. This does not mutate/modify the original array, however, it's only available in Python 3+. If you wish to achieve the same in earlier versions of Python, then you can do the following instead:

existing_list = ['foo', 'bar']
new_list = existing_list + ['baz']

print(new_list) # ['foo', 'bar', 'baz']

Here, the + operator creates a shallow copy of both lists and combines them — where the first list is the existing one and the second one has the value you wish to add to the end/tail of the new list.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.