Image

The Python Coding Stack: What's the Difference Between Zipping and Unzipping Your Jacket? • Unzippin

Today's post is short and visual. You probably used Python'szip()before. (But if you haven't, you'll figure out what it does in this article, so don't worry!)

But how often have you used Python'sunzippingtool?

Eh?! Did you miss this? Do you want to go and have a look for this tool in your IDE or the Python docs? I'll save you the trouble. You won't find it.

But Pythondoeshave an unzipping tool, I promise. Confused? Let's start.

Terminology note: As regular readers may have noticed, I use British English in articles on The Stack, with occasional translations to the US variant when needed. In British English,zipis both the noun and the verb—we don't use the wordzipper. However, to differentiate between the clothing zip like the one on your jacket and Python'szip(), I'll use the US English variantzipperto refer to the clothing type.

Zipping • Meet the Team

Meet the team. There are three lists with the names, ages, and locations of four team members in some nondescript team:

Let's visualise these lists:

If you had a choice, you might have chosen to use a single data structure to store these related items since the first number inagesis the age of the first person innames, and the first city inlocationsis where he's located, and so on. But you don't always have a choice. So, let's assume this is what you have, and you need to work with three separate data structures.

In the Python program, there's no connection between elements from the different lists. The only connection is between elements within each list since they're members of the same list.

But you can zip these three lists together. And this works (almost) in the same way as the zipper on your jacket. One difference is that you can zip as many things as you want. The clothing zipper can only zip two sides of the garment.

Let's add zippers to our lists so you can see this better:

Time to zip up:

If I had more time, I'd figure out a way to create an animation for the next phase. But your imagination will have to do instead. Zip up both sets of zippers:

The zipping action brings elements from different lists together. So,"James",20, and"London"are now connected following the call tozip(). Sincezip()returns aniterator, you can usenext()to confirm that the iterator’s first element contains these three items:

And why not confirm the rest as well?

Each trio of name, age, and location is grouped within a tuple. Let's visualise the new groupings:

If you try to callnext()again, you'll get aStopIterationexception. Read more about this process in this article if you're interested:The Anatomy of a `for` Loop.

If you're following along in the REPL, you'll now need to recreate thezipobjectteam_memberssince the calls tonext()above exhausted the iterator:

Support The Python Coding Stack

Sorting by age

Now, let's sort the team members by age, from youngest to oldest. You can't simply sort the listagessince you also want to rearrange the respective names and locations. You can use thezipobject you just created,team_members:

You sort the tuples yielded by thezipobjectteam_membersusing the built-insorted(). You use the function'skeyparameter to ensure you sort using the second element (index =1) from each tuple. You can read more aboutsorted()and thekeyparameter, which you also find in other places in Python, here:The Key To The `key` Parameter in Python.

And if you don't likelambdafunctions, you can useoperator.itemgetter(1), which is also more efficient. But that's taking us off course, so let's move on.

Here's the visual representation of the sorted groupings, which are tuples. They’re ordered based on the person’s age:

Do you want to join a forum to discuss Python further with other Pythonistas? Upgrade to a paid subscription here on The Python Coding Stack to get exclusive access toThe Python Coding Place's members' forum. More Python. More discussions. More fun.

Subscribe now

And you'll also be supporting this publication. I put plenty of time and effort into crafting each article. Your support will help me keep this content coming regularly and, importantly, will help keep it free for everyone.

Unzipping

But, you still want to have separate lists for the names, ages, and locations, as this was the original format of your data.

You started off with three separate data structures,names,ages, andlocations. Recall how there was no connection within Python between elements of these different lists.

Thezip()call solved this problem by linking elements from the three lists together. This allowed you to sort them while ensuring that the names and locations swap places along with the ages.

But now you have a connection between a name, an age, and a location, as each tuple contains one of each. However, you no longer have connections between all the names, all the ages, and all the locations.

So, you need to zip the four tuples together! Recall thatzip()can take any number ofiterablesas arguments. Earlier in this article, you zipped three iterables: the listsnames,ages, andlocations.

Now, you can zip the four tuples stored in the listsorted_team. Let's add zippers to these four tuples:

You need to zip these together:

Conceptually, you'd like to write something like this:

zip( ('Sarah', 19, 'Vancouver'), ('James', 20, 'London'), ('Kate', 34, 'Sydney'), ('Bob', 54, 'San Francisco'), )

You'd need to pass the four tuples as four positional arguments inzip(). But doing this by hand is too much work. We want to be lazy.

You have a list that contains all these tuples—the listsorted_team. However, you can't simply pass the list tozip()since the list is just one iterable, butzip()needs two or more iterables to zip them together.

Instead, you can unpack the list using the unpacking operator*. Let's return to our REPL session to complete this:

And here's the visual representation:

You started with the three listsnames,ages, andlocations.

You zipped them together to create groupings, each containing a name, an age, and a location.

The zipping enabled you to sort these three-tuples (tuples each containing three items) using the person's age.

Finally, you unzipped the result to get back to having three separate iterables:names,ages, andlocations. Since these iterables are returned by thezip()call, they're tuples, not lists. But you can cast them to lists if that's what you want.

Note that the built-insorted()returns a list, which you then unpack within the call tozip()to unzip its contents. You may use other tools in between zipping and unzipping that return iterators or any other iterable. The process remains the same. You'll still need to unpack the final iterable within the call tozip()using the unpacking operator*.

Final Words

So, Python does have an unzipping tool, after all. It's the same tool you use to zip up:zip(). The unzipping process requires the additional step of unpacking the iterable you got from the originalzip()and any further processing performed on the data before unzipping.

And that's exactly what you do with your jacket zipper. You use the same zipper to zip up and unzip. You simply reverse the motion.

Image byTumisufromPixabay

Image of zipper used in diagrams byNina GarmanfromPixabay

Code in this article uses Python 3.13

The code images used in this article are created usingSnappify.[Affiliate link]

You can also support this publication by making aone-off contribution of any amount you wish.

Support The Python Coding Stack

For more Python resources, you can also visitReal Python—you may even stumble on one of my own articles or courses there!

Also, are you interested in technical writing? You’d like to make your own writing more narrative, more engaging, more memorable? Have a look atBreaking the Rules.

And you can find out more about me atstephengruppetta.com

Further reading related to this article’s topic:

A One-Way Stream of Data • Iterators in Python (Data Structure Categories #6)

Iterable: Python's Stepping Stones

The Anatomy of a for Loop

The Key To The key Parameter in Python

Appendix: Code Blocks

Code Block #1
names = ["James", "Bob", "Kate", "Sarah"] ages = [20, 54, 34, 19] locations = ["London", "San Francisco", "Sydney", "Vancouver"]
Code Block #2
team_members = zip(names, ages, locations)
Code Block #3
next(team_members) # ('James', 20, 'London')
Code Block #4
next(team_members) # ('Bob', 54, 'San Francisco') next(team_members) # ('Kate', 34, 'Sydney') next(team_members) # ('Sarah', 19, 'Vancouver')
Code Block #5
team_members = zip(names, ages, locations)
Code Block #6
sorted_team = sorted(team_members, key=lambda grouping: grouping[1]) sorted_team # [('Sarah', 19, 'Vancouver'), ('James', 20, 'London'), # ('Kate', 34, 'Sydney'), ('Bob', 54, 'San Francisco')]
Code Block #7
names, ages, locations = zip(*sorted_team) names # ('Sarah', 'James', 'Kate', 'Bob') ages # (19, 20, 34, 54) locations # ('Vancouver', 'London', 'Sydney', 'San Francisco')

For more Python resources, you can also visitReal Python—you may even stumble on one of my own articles or courses there!

Also, are you interested in technical writing? You’d like to make your own writing more narrative, more engaging, more memorable? Have a look atBreaking the Rules.

And you can find out more about me atstephengruppetta.com

https://www.thepythoncodingstack.com/p/python-unzipping-using-zip