how.wtf

Spread operator in Python

· Thomas Taylor

The JavaScript spread operator (...) is a useful and convenient syntax for expanding iterable objects into function arguments, array literals, or other object literals.

Python contains a similar “spread” operator that allows for iterable unpacking. Each of the examples below will demonstrate the comparison between the two languages.

Function Arguments

JavaScript:

1function multiply(a, b) {
2    return a * b;
3}
4const numbers = [3, 5];
5console.log(multiply(...numbers));
6// Output: 15

Python:

1def multiply(a, b):
2    return a * b
3numbers = [3, 5]
4print(multiply(*numbers))
5# Output: 15

Array Literals

1const numbers = [1, 2, 3];
2const newNumbers = [0, ...numbers, 4]
3console.log(newNumbers);
4// Output: [ 0, 1, 2, 3, 4 ]
1numbers = [1, 2, 3]
2new_numbers = [0, *numbers, 4]
3print(new_numbers)
4# Output: [0, 1, 2, 3, 4]

Object Literals

1const testObj = { foo: 'bar' };
2console.log({ ...testObj, foo2: 'bar2' });
3// Output: { foo: 'bar', foo2: 'bar2' }

A very similar technique can be applied with Python dictionaries. Notice the double asterisk operator (**).

1test_obj = { 'foo': 'bar' }
2print({ **test_obj, 'foo2': 'bar2' })
3# Output: {'foo': 'bar', 'foo2': 'bar2'}

To unpack keyword arguments, the double asterisk operator (**) is used. In contrast, the single asterisk operator (*) is used for iterable objects.

#python  

Reply to this post by email ↪