When it comes to learning a programming language, one thing you’ll have to get used to doing is manipulating data. Perhaps the first time you’ll be asked to do that is through a variable swap.
As it turns out, swapping variables is pretty straightforward as long as you’re willing to introduce a temporary variable. If not, Python let’s you take advantage of iterable unpacking: `a, b = b, a`python.
If you want to learn more about how these two solutions work, keep reading. Otherwise, I’m glad I could help! Consider swinging by my list of ways to grow the site to keep content like this coming.
Table of Contents
A common “toy” problem in programming is to ask someone to swap two variables. Basically, this means taking the contents of one variable and moving it to another variable and vice versa.
Unfortunately, I find that a lot of times you’re asked to perform this task, it never really makes sense in context. After all, why would you ever need to swap two variables? If both values are already stored, it seems like it would make more sense to just pick the one that you need at the right time.
As it turns out, however, there are some valuable uses for swapping. For example, we might have a pair of variables which represent a palette of abilities in a video game (if you can’t tell, I’ve been playing a lot of PSO2):
palette_1 = "foie" # a fire ability palette_2 = "barta" # an ice ability
In this game, we’re able to swap palettes on-the-fly. As a result, we might have a palette dedicated to fire abilities and another palette dedicated to ice abilities. That way, we can handle different types of enemies as they stumble into our path.
To keep it simple, the active palette will always be the first palette. In other words, when we switch palettes, we’re really swapping abilities into the active palette. Of course, we don’t want to lose anything in the previously active palette, so we have to perform a swap.
Ultimately, the question becomes: “what is the best way to perform this swap?” That’s the goal of the remainder of this article.
Seeing as swapping variables is a relatively straightforward task, I could only think of two practical ways of getting it done. Honestly, I had considered including a third, but I’d hate to see it used in code in the wild. That said, I’m always open to creating an article on solutions that never made the cut.
At any rate, below you’ll find the two main ways of swapping variables. Generally, there is only one reasonable way to do this (i.e. using a temporary variable), but Python was nice enough to include a bit of syntactic sugar (i.e. iterable unpacking). Naturally, we’ll look at both solutions.
Swap Elements with a Temporary Variable
palette_1 = "foie" palette_2 = "barta" _ = palette_1 palette_1 = palette_2 palette_2 = _
This works because we copy the reference to the first palette in a new variable. Now, both `palette_1`python and our temporary variable reference the same value, “foie”. As a result, it’s safe to overwrite `palette_1`python.
At this point, both `palette_1`python and `palette_2`python reference the same value, “barta”. All that’s left is to overwrite `palette_2`python with the value of the temporary variable. In the end, `palette_1`python stores “barta” and `palette_2`python stores “foie”.
Also, if you’re unfamiliar with python, the underscore, `_`python, is the community’s stylistic way of denoting a temporary variable. In other words, it’s a variable that we don’t plan on using. Feel free to use it in scenarios like this where you explicitly want to ignore the value that it stores.
Swap Elements with Iterable Unpacking
As mentioned already, the previous solution is perfectly valid. In fact, it’s the solution I’d expect to see in most programming languages. That said, Python has a nice iterable unpacking feature which can be used to convert a list-like data structure into a set of variables.
Oddly enough, this same exact feature can be used to swap variables as long as our variables are in some list-like structure:
palette_1 = "foie" palette_2 = "barta" palette_1, palette_2 = palette_2, palette_1
This solution works because the righthand side of the statement places our two variables in a tuple—which is an immutable list. The following code snippet works exactly the same way:
palette_1 = "foie" palette_2 = "barta" _ = palette_2, palette_1 # creates a tuple from the two palettes palette_1, palette_2 = _
Once they’re a tuple, we can take advantage of iterable unpacking by converting the tuple back into a pair of variables.
Of course, this statement would be totally pointless if it weren’t for one important detail: each side of the expression must appear reversed. In other words, if the tuple is in the form (a, b), then we must unpack them in the opposite order (b, a). That way, the swap occurs properly.
Overall, I really like this solution, and I think it’s quite a bit more intuitive than introducing an extra variable. That said, it’s up to you to decide which solution you like. Perhaps some performance metrics will help you decide.
As always, I like to take all of the solutions from each article and run them through a quick performance test. To do that, we’ll need to store each solution in a string:
setup = """ palette_1 = "foie" palette_2 = "barta" """ temp = """ _ = palette_1 palette_1 = palette_2 palette_2 = _ """ unpack = """ palette_1, palette_2 = palette_2, palette_1 """
Here, we created three strings: one for each solution and one to introduce our strings. Naturally, all we have to do now is import our testing utility, `timeit`python, and we’ll be ready to go:
>>> import timeit >>> min(timeit.repeat(setup=setup, stmt=temp)) 0.02269350000005943 >>> min(timeit.repeat(setup=setup, stmt=unpack)) 0.01923110000007
Welp, you can’t really get code any faster than that. For reference, I’m running Python 3.8.2 on a Windows 10 machine.
That said, it looks like there’s not much of a performance advantage either way. For my own sanity, I ran this a few more times, and the results were always the same. Feel free to run it yourself and see what you get.
Also, if you’re interested in learning how these tests work, I recommend checking out my article on performance testing. Otherwise, check out the challenge below for a way you can contribute to The Renegade Coder community.
When I was putting this article together, I had originally titled it “How to Swap Elements of a List in Python.” Of course, I quickly realized that there was a simpler problem to be addressed first: the swapping of variables.
That said, I still think being able to swap elements in a list is a valuable skill. In fact, all in-place sorting algorithms depend on swapping, so it’s definitely worth learning.
However, instead of giving away the solution, I thought it would be fun to pool some community solutions under the #RenegadePython tag on Twitter. In other words, how would you leverage what we learned in this article to swap elements in a list? Here’s my solution:
If you figure it out, feel free to share! If you don’t have Twitter, you’re welcome to share directly in the GitHub repo.
A Little Recap
Welp, it looks like all we had today were two solutions. Here they are:
palette_1 = "foie" palette_2 = "barta" # temp variable solution _ = palette_1 palette_1 = palette_2 palette_2 = _ # iterable unpacking solution palette_1, palette_2 = palette_2, palette_1
Hopefully, you got some value out of this article. If so, I’d appreciate it if you took some time to check out my list of ways to grow the site. Right now, I’m trying to grow my Discord, but I’d love it if you could help in any way.
Likewise, here are some related articles:
- How to Check If a Key Exists in a Dictionary in Python: in, get(), and More
- How to Loop Over a Dictionary in Python: Keys, Values, and More
In addition, here are some resources from the folks at Amazon (ad):
- Effective Python: 90 Specific Ways to Write Better Python
- Python Tricks: A Buffet of Awesome Python Features
- Python Programming: An Introduction to Computer Science
Otherwise, thanks for stopping by! I appreciate it. Take care.
I'm embracing the virtual world and moving all of my computer science exams online. Here's why!
Amid all the chaos of my daily TODO list, I was able to find order by sorting my tasks by my values. Maybe you'll find some "value" in this tip as well.