Tuesday, October 11, 2016

Python and simultaneous assignment

I'm taking a little break from Javascript at the moment to pick up Python. While I know some C and JS and have seen that they share a lot of similarities in syntax structure Python is a completely new animal to me (pun totally not intended).

While I could list off the syntactical differences there are some things that Python can do that make life just a little bit easier for the average programmer. I plan to bring those up as I continue to make my way through learning the language and in that spirit I present the first "huh, that's cool" difference: Simultaneous assignment.

For today's moment let's compare Python to C. Let's say the first thing we want to do is create two integer variables and then assign the first variable (num1 in our example) the value of 4, and the second (num2) we want to assign the value 0.

In C we would go about doing this with statement something like this:

C program to for this example

Pretty simple right? We declare the types and then through separate statements assign them each their respective values.

So what can you do with Python?

Python program to accomplish the same task
Pretty cool, right? Python was able to create the variables and assign them the correct values in 1 line of code while it took C to do so. It's not earth shattering or anything but more compact (though still readable!) code is nearly always better. But that's not the only thing that is super cool about this feature:

Let's say we're faced with a classic problem in programming, needing to switch the values in two variables. So in our example we would like num1 to equal 0 and num2 to equal 4 after initially being assigned the values of 4 and 0 respectively.

In C we'd have to do this tried and true solution:

In which we create a third helper variable to hold the value from one of the other variables, change the value of the variable that we just copied to the helper variable to the other "main" variable, and then finally assign the helper variable's value to the original value. That's a decent amount of code just to switch the values of two variables!

So how does Python handle this?:

That's it, just like the assignment of the initial values you can simultaneously switch the values in one statement. No helper variables, no multiple lines of code to juggle the values around, just beautiful simultaneous switching. It won't change the world but it's a nice feature all the same!

No comments:

Post a Comment