If you are already using ES6
you must be pretty familiar with destructuring
by now. As a refresher, destructuring
allows us to assign the properties of an array/ object to individual variables, without accessing those properties using the .
notation.
So instead of doing this:
const someNumbersJs = [3, 6, 9];
const oneJs = someNumbers[0];
const twoJs = someNumbers[1];
const thereJs = someNumbers[2];
... we could do the same thing using a much shorter code:
const [oneJs, twoJs, threeJs] = someNumbersJs;
console.log(oneJs); // prints 3
console.log(twoJs); // prints 6
console.log(threeJs); // prints 9
In Python
we can also destructure (unpack
) items from a list
(Python doesn't have a native array
data structure but a list looks identical to a Javascript array). The syntax would look like so:
someNumbersPy = [3, 6, 9]
[onePy, twoPy, threePy] = someNumbersPy
print(onePy) #prints 3
print(twoPy) #prints 6
print(threePy) #prints 9
We can skip items in the list, just like in Javascript. In Python we skip them using an _
and not a comma (,
).
Javascript
const [oneJs, , threeJs] = someNumbersJs
Python
[onePy, _, threePy] = someNumbersPy
We can also use the rest
operator - in Python is represented by an *
, while in Javascript by an ellipsis (...
):
Javascript
const [oneJs, ...restJs] = someNumbersJs;
console.log(restPy); // prints [6, 9]
Python
[onePy, *restPy] = someNumbersPy
print(restPy) #prints [6, 9]
VERY NICE FEATURE: Compared to Javascript where the rest
operator must be the last element in the array, in Python
we can use it wherever we want, so we could do something like this:
otherNumbers = [528, 79, 2456, 1203, 74, 1]
[first, *restPy, last] = otherNumbers
print(first) #prints 528
print(rest) #prints [79, 2456, 1203, 74]
print(last) #prints 1
Trying to do the same thing in Javascript will throw an error. Pretty neat, right?
Image source: Christina Morillo/ @divinetechygirl on Pexels
Top comments (5)
wonderful topic, really thanks π
You're welcome π
Thank you for mentioning.
Nice to know that you can do stuff like this so useful.
Hey, I found a similar blog about this here- damianfallon.blogspot.com/2020/09/...