Unpacking Python lists vs. destructuring Javascript arrays

Unpacking Python lists vs. destructuring Javascript arrays:

 

https://damianfallon.blogspot.com/

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?

https://damianfallon.blogspot.com/

from Tumblr https://generouspiratequeen.tumblr.com/post/630240055550787584

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s