Python Tuple Unpacking in ES6
July 09, 2017
Python developers often get to use a really cool feature called tuple unpacking. They(We) can return more than one values, assign to two variables simultaneously etc.
Tuple and Tuple Unpacking
Just in case if you don’t know what tuple and tuple unpacking means. Tuple is a data type of Python programming language. It has a lot of similarities with lists/Arrays but the main difference that we should keep in mind is that tuple is an immutable data type. Which means, once constructed you can’t change the elements of a tuple.
Tuple Unpacking basically works with lists too in Python but it is kind of common to use tuples instead. Let’s say you want to declare two variables with their initial value of 11 and 22. How would you do it? Basically, you can do it in the simple way or the cool way.
# Simple waya = 11b = 22# Cool waya, b = 11, 22
The second way is where I am using tuple unpacking. Tuple unpacking just works like that. When you are assigning to more than one variables at once python checks the right side of the assignment operator for an iterable object like tuples or lists. If it can’t find one it raises an error. The next thing python looks at is the size or length of the object and number of variables. If they don’t match Python raises an error. Finally if none of the above errors are raised then python takes the variables and values inside the object one by one and assigns the values to the variables respectively.
Let me show an example how tuple unpacking might make your life easier.
# Swapping two variables# Boring...a = 22b = 44t = aa = bb = t# Cool Waya, b = 22, 44a, b = b, a
var [a, b] = [22, 44]console.log(a) // 22console.log(b) // 44
var [a, b] = console.log(a) // 22console.log(b) // undefinedvar [c, d] = [11, 22, 33]console.log(c) // 11console.log(d) // 22// 33 does not get assigned
var [a, b] = [22, 44]console.log(a, b)[(a, b)] = [b, a] // 22 44console.log(a, b) // 44 22
This feature now works natively in Chrome 51+ and Firefox 47+. So, I think its fair to say that this feature is almost available to use. But to be safe we should always use transpilers for these new ES6 codes.
This is the first blog post that I have ever written. So there are bound to be some mistakes. I am a human and I don’t know everything. I’d love to hear from you about other features or techniques you like to use on your code. Let me know if this post helped you in any way. :)