• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Data Dependence

Data Dependence

Learn about software development. Covering topics such as Coding in Python and JavaScript, developer productivity and more.

  • Home
  • Top Resources
  • Who Are You?
  • Show Search
Hide Search
You are here: Home / Programming / How to Write Beautiful Code with Pythonic Idioms | Unpacking

How to Write Beautiful Code with Pythonic Idioms | Unpacking

· · Leave a Comment

This is the third in a series of posts on common pythonic idioms, so if you haven’t seen the previous two, you should definitely go and give them a read.

This post is all about unpacking, that is, splitting sequences into other variables. However as you will soon see, they have some very convenient and surprising uses. Let’s get started.

HOW TO UNPACK SEQUENCES AND DO AMAZING THINGS WITH THEM

Unpacking works on Python sequence types and divides the contents of said sequence type into other variables. Are you starting to see a pattern? Sequence types come up at lot in Python and have many built in functions associated with them with many useful implementations. Live them, breathe them, master them.

How to unpack sequence types

The first thing you are probably wondering is how to actually do unpacking. The syntax is very simple.

#How to unpack
user = [0, 180, 75]
user_id, height, weight = user
name = ("Jamal", "Moir")
f_name, l_name = name

As you can see, all you do is take your list, tuple or range and new variables, one for each item in the sequence and then assign the sequence to the new variables. You should note that to do this you need to know how many items the sequence contains.

Swapping variables with unpacking

This is a brilliant little gem within the Python programming language. If you ever need to swap variables, you should definitely use this compact and efficient Python idiom.

#How not to swap variables
temp = a
a = b
b = temp
#How to swap variables with unpacking
a, b = b, a

There’s not really much to say about this. It’s simple, easy and brilliant.

Using unpacking with enumerate()

We’ve already seen this in the For Loops post in this series, but it’s worth visiting again in the context of unpacking.

#How to use unpacking with enumerate()
for i, val in enumerate(primes, 1):
  print("{prime} is prime number {n}.".format(prime=val, n=i))

As explained before, enumerate creates a tuple of size two. In this example we then use unpacking to access the separate parts of the created tuple allowing us to use more reader-friendly names within the for loop.

Using extended unpacking

New to Python 3 is ‘extended unpacking’ an improvement on unpacking which allows you to specify a variable which can have a list of values unpacked into it. I have included what each variable contains after the unpacking as a comment after it.

#How to use extended unpacking
a, *b, c = range(10) #a = 0, b = [1, 2, 3, 4, 5, 6, 7, 8], c = 9
d, *e = range(10) #d = 0, e = [1, 2, 3, 4, 5, 6, 7, 8, 9]

The variable with an asterisk before them are the variable that will contain the list if there are more values to unpack than there are variables to unpack into. Note that this allows you to unpack sequences of unknown length.

Using throw-away variables with unpacking

If you want to unpack a sequence but don’t want to use all the values, you can use a throw-away variable to go about doing this.

#temporary variable
user = ["Jamal", "Moir", "07778889999"]
f_name, __, phone_no = user
print("Hello {name}, your phone number is {no}.".format(name=f_name, no=phone_no))

In the above example we use a double underscore for a throw-away variable. A single underscore can also be used but according to python-guide.org can sometimes cause problems.

This was the third in a series of posts on common pythonic idioms, I hope you managed to get something out of it. The more Python idioms I learn, the more fun it becomes to program in the language and the more I come to I come to like it.

Don't forget to share and follow!

Remember, don't forget to share this post so that other people can see it too! Also, make sure you subscribe to this blog's mailing list and follow me on Twitter so that you don't miss out on any useful posts!

I read all comments, so if you have something to say, something to share or questions and the like, leave a comment below!

‘Ello, I’m Jamal – a Tokyo-based, indie-hacking, FinTech software developer with a dependence on data.

I write Shakespeare-grade code, nowadays mostly in Python and JavaScript and productivity runs in my veins.

I’m friendly, so feel free to say hello!

Twitter is the best place for a chat.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Pocket (Opens in new window)

Related

Programming idioms, python, pythonic, unpacking

Primary Sidebar

LEVEL UP with the Data Dependence Newsletter! Subscribe!


Top Posts & Pages

  • How to Find Unclosed Tags and Brackets Using a Stack
  • How to Build a GUI in Python 3.5
  • Mocking in Python - How to Bypass Expensive and External Code Within Your Tests
  • How to Logically Group Your Python Code into Modules
  • A Quick Guide to Slicing in Python - Become a Python Ninja

Data Dependence

Copyright © 2023 · Monochrome Pro on Genesis Framework · WordPress · Log in

  • Home
  • Top Resources
  • Who Are You?