In Python, to add a value to the front and return a new list
(as opposed to modifying it in-place), you can do the following:
# Python 3+ existing_list = ['bar', 'baz'] new_list = ['foo', *existing_list] print(new_list) # ['foo', 'bar', 'baz']
In the example above, the value you wish to add to the front goes at the first index in the new list
and the existing list is unpacked (using *
) 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 = ['bar', 'baz'] new_list = ['foo'] + existing_list print(new_list) # ['foo', 'bar', 'baz']
Here, the +
operator creates a shallow copy of both lists and combines them — where the first list
has the value you wish to add to the start and the second list
is the existing one.
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.