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.
Hope you found this post useful. It was published . Please show your love and support by sharing this post.