Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Dictionaries Packing and Unpacking Dictionaries

Vedang Patel
Vedang Patel
7,114 Points

I am really confused with packing and unpacking

I am confused how did you get everything printed I really don't understand the concept of packing and unpacking

3 Answers

cm21
cm21
150,854 Points

Hi Vedang,

I recommend the following article: http://hangar.runway7.net/python/packing-unpacking-arguments. It concerns the use of the asterisk and double-asterisk (* and **, respectively.) They're used to pack the arguments that a method takes into a tuple. Unpacking allows the programmer to pass packed arguments to different methods.

Uses for packing/unpacking (from the linked article):

"Combined together packing and unpacking lets you do a lot of things like:

  • validate arguments before passing them on
  • set defaults for positional arguments
  • create adaptors for different pieces of code / libraries
  • modify arguments depending on context
  • log calls to methods
  • write better and more resilient wrappers"

Hope this helps!

In my 'real life' I have to do a bunch of string manipulation, so I use lots of regular expressions (ack! hard but very useful) and tuples. As unpacking results in tuples, packing sets up the argument, so it's a natural. I found this article in Stack Overflow very useful: "http://stackoverflow.com/questions/3753589/packing-and-unpacking-variable-length-array-string-using-the-struct-module-in-py" when trying to recall what I'd learned. I hope it's helpful to you :)