Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 23, 2020 06:48 pm GMT

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];

... we could do the same thing using a much shorter code:

const [oneJs, twoJs, threeJs] = someNumbersJs;console.log(oneJs); // prints 3console.log(twoJs); // prints 6console.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 3print(twoPy) #prints 6print(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] = otherNumbersprint(first) #prints 528print(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


Original Link: https://dev.to/cilvako/unpacking-python-lists-vs-destructuring-javascript-arrays-3mog

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To