Say you have a dictionary that you want to both copy and update. In JavaScript, this is a common pattern that gets its own syntax, called the object spread operator:
const oldObject = { hello: 'world', foo: 'bar' }
const newObject = { ...oldObject, foo: 'baz' }
After running this snippet, newObject
will be { hello: 'world', foo: 'baz' }
. Turns out, you can also do this in Python since version 3.5:
old_dict = {'hello': 'world', 'foo': 'bar'}
new_dict = {**old_dict, 'foo': 'baz'}
new_dict
# Expected result
# {'hello': 'world', 'foo': 'baz'}
You can refer to the double asterisk **
as “dictionary unpacking”. You sometimes see it for passing extra keyword arguments into a function.
Spread operator for lists
In JavaScript, you can also use spread operators in arrays to make updated copies:
const oldArray = [1, 2, 3]
const newArray = [...oldArray, 4, 5]
This would make newArray
an updated copy with [ 1, 2, 3, 4, 5 ]
.
We can replicate the behavior for lists in Python:
old_list = [1, 2, 3]
new_list = [*old_list, 4, 5]
new_list
# Expected result
# [1, 2, 3, 4, 5]
This is somewhat less useful since you can also write old_list + [4, 5]
, which doesn’t exist in JavaScript. But the spread operator approach is still a cool trick to know and being comfortable with basic data structures in Python is important! You can refer to the single asterisk *
as “iterable unpacking” or “splat”.