How to Append a Value to a Python List?

Find out how you can append a value to a list in Python

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']

Hope you found this post useful. It was published . Please show your love and support by sharing this post.