How to Append a Value to a Python List?

In Python, you can append a value to an existing list by using the list.append() method, for example, like so:

l = ['foo', 'bar']
l.append('baz')

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

This would do in-place modification of the list (as opposed to returning a new one) — which means that it would mutate/modify the original list.

You can shorten this by using slice assignment (list[-1:0] = [value]), for example, like so:

l = ['foo', 'bar']
l[-1:0] = ['baz']

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

This is the known as the extended indexing syntax — where specifying [-1:0] as the start and stop values to the slice operator respectively, appends the value (e.g. ['baz']) to the list. This is similar to using the slice function (slice(start, stop)):

l = ['foo', 'bar']
l[slice(-1, 0)] = ['baz']

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

In both the examples above, "-1" can be replaced by len(list), for example, like so:

l = ['foo', 'bar']
l[len(l):0] = ['baz']

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

In this case, 0 from the right side can be omitted:

l = ['foo', 'bar']
l[len(l):] = ['baz']

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

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.