The JavaScript spread operator(...) becoming popular in programming as it is used for expanding iterable objects into function arguments, array literals, or other object literals.
Simply saying, spread operator can be used as an unpacking tools which expands the iterables into individual elements
On the other hand, Python too contains an alternative for Spread operator
that allows the iterables unpacking.
Now we will see it in some of the examples shown-
Array Literals
In JS
const name = ['Aditya', 'Shivam', 'Yash'];
const newname = ['Sahil', ...name, 'Niraj']; //spreading name in newname
console.log(newname);
//Output:['Sahil', 'Aditya', 'Shivam', 'Yash', 'Niraj']
Similarly,
In Python
name = ['Aditya', 'Shivam', 'Yash']
newname = ['Sahil', *name, 'Niraj']# unpacking name in newname
print(newname)
#Output: ['Sahil', 'Aditya', 'Shivam', 'Yash', 'Niraj']
As we can see, we achieved the same result in Python as we got using the spread operator in JS.
Function Arguments
In JS
function add(a,b){
return a+b;
}
const nums = [20,30];
console.log(add(...nums));//spreading nums while passing argument to a function
//Output: 50
Similarly,
In Python
def add(a,b):
return a+b
nums = [20,30]
print(add(*nums)#unpacking nums list while passing it to the add method
Here we used the approach to get the similar output as we got in JS using spread operator.
Object Literals
In JS
const person = {
name : 'Aditya',
age : '23',
occupation : 'Developer',
height:'170 cm'
}
console.log({...person,location : 'India'})
//Output: {name: 'Aditya', age: '23', occupation: 'Developer', height: '170 cm', location: 'India'}
Similarly, in Python we can use the double asterisk operator (**
)
In Python
person = {
'name' : 'Aditya',
'age' : '23',
'occupation' : 'Developer',
'height' : '170 cm'
}
print({**person, 'location':'India'})
//Output: {'name': 'Aditya', 'age': '23', 'occupation': 'Developer', 'height': '170 cm', 'location': 'India'}
As we can see, we needed **person
to unpack the keyword arguments. Whereas, single asterisk operator *nums
is used for iterable objects.