DEV Community

Cover image for Unpacking Python lists vs. destructuring Javascript arrays
Arika O
Arika O

Posted on • Updated on

Unpacking Python lists vs. destructuring Javascript arrays

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];
Enter fullscreen mode Exit fullscreen mode

... 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Python

[onePy, _, threePy] = someNumbersPy 
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

Python

[onePy, *restPy] = someNumbersPy 
print(restPy) #prints [6, 9]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
amirdarx profile image
amir

wonderful topic, really thanks 💛

Collapse
 
arikaturika profile image
Arika O

You're welcome 🙌

Collapse
 
arikaturika profile image
Arika O

Thank you for mentioning.

Collapse
 
andrewbaisden profile image
Andrew Baisden

Nice to know that you can do stuff like this so useful.

Collapse
 
vyvyvi profile image
Vyvy-vi (Vyom Jain) • Edited

Hey, I found a similar blog about this here- damianfallon.blogspot.com/2020/09/...