Packing and Unpacking in Python (2024)

Packing is a handy Python tool that provides a dynamic way to pack and unpack values into a single data structure or take them out and assign them to multiple variables. This process greatly improves the reliability and adaptability of your code.

In Python, “packing” refers to the process of putting values into a new tuple or list by separating them with commas. This can be done with an assignment statement where the left-hand side is a tuple or list of variables and the right-hand side is another tuple or list of values.

For example, you might have three variables, which are number1, number2 and number3, which are defined as such:

1

2

3

number1 = 1

number2 = 2

number3 = 3


You can pack those variables into a tuple like so:

1

myTup = (number1, number2, number3)


Or a list like so:

1

myList = [number1, number2, number3]


You can also use the * operator (which is used as both power and multiplication operators). Before we see how that works with packing, let me show you how the * operator works. We’ll define a function called sumOf and use the * operator like so:

1

2

3

4

def sumOf(*nums):

print('Our numbers are:', nums)

return sum(nums)

print('Adding them up, we get:', sumOf(10, 20, 30))

Know that *nums stores the series of numbers and then the sum() function adds them together. So, when run, the output of the above would be:


Back to packing, we can use the * operator with packing like so:

1

2

3

4

num1=1

num2=2

num3=3

*num,=num1,num2,num3


But how do we use packing in actual Python code?

Packing with Tuples

Remember, a tuple is an immutable list, so it cannot be changed once created. Tuples are great options for storing data that you don’t want to be modified. Let’s say we want to create a simple program, using tuples and packing to sum up a string of numbers. We’ll define our custom function as such:

1

2

addPack(*myTuple):

return sum(myTuple)


Above, we’re sending a dynamic number of arguments to the addPack function and are accessing them via a single myTuple parameter by using the * operator.

Next, we pack our arguments with the following two lines:

1

2

print(addPack(2, 3, 4, 5, 6, 7, 8))

print(addPack(5, 10, 15, 20))


Because we’re using dynamic arguments for packing, we could have continued with our numbers like so:

1

2

print(addPack(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15))

print(addPack(5, 10, 15, 20, 25, 30, 35, 40))


When we run the application, it will add the numbers in both tuples and total them together. What this has done is pack the addPack function with variables from the print functions.

You can also collect multiple values with packing and use certain parts in different ways. Take, for instance, this piece of Python code:

1

2

3

4

5

name="John Jacob Jinglheimer Schmidt"

first_name, *rest_name=name.split()

print("Complete Name:", name)

print("First Name Only:", first_name)

print("Remaining names:", rest_name)


The above performs what is called a string split to collect only the first name of someone with multiple names. What this does is collect the first name in one variable and the remaining names into another (hence the string split).

The output of the above packing example would be:

1

2

3

Complete Name: John Jacob Jinglheimer Schmidt

First Name Only: John

Remaining names: ['Jacob', 'Jinglheimer', 'Schmidt']

Unpacking with Tuples

In Python, unpacking is the process of extracting values from a sequence and assigning them to multiple variables. We achieve unpacking with the assignment operator on the left side and an iterable object on the left side.

For example, we can unpack with a tuple like so:

1

2

3

myTuple = (1, 2, 3)

a, b, c = myTuple

print(myTuple)


The output of the above would be:

1

(1, 2, 3)


Another example of unpacking a tuple looks like this:

1

2

3

4

5

6

fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)

print(yellow)

print(red)


What we’ve done is assign values to multiple variables and then unpack them. The output of the above script would be:

1

2

3

apple

banana

cherry


We can unpack a list like this:

1

2

3

myList = [10, 20, 30]

a, b, c = myList

print(myList)


The output of the above would be:

1

[10, 20, 30]


We can also unpack dictionaries (an unordered collection of data in the format of a key-value pair) like so:

1

2

3

myDict = {'fname': 'Jack', 'lname': 'Wallen', 'country': 'USA'}

fname, name, country = myDict.values()

print(myDict.values())


The output of the above script would be:

1

dict_values(['Jack', 'Wallen', 'USA'])


Unpacking allows you to assign values from a sequence to multiple variables, using only a single line of code.

By using packing and unpacking you can create assignments with a single statement and catch several values with a single identifier, thereby making your code much easier to read. These two features allow for much more flexible handling of function arguments and streamlined data manipulation.

TRENDING STORIES

Jack Wallen is what happens when a Gen Xer mind-melds with present-day snark. Jack is a seeker of truth and a writer of words with a quantum mechanical pencil and a disjointed beat of sound and soul. Although he resides... Read more from Jack Wallen
Packing and Unpacking in Python (2024)
Top Articles
An Introduction to JSX - React JSX
SBI Debit Card Tracking - How To Track SBI Debit Card?
Toa Guide Osrs
Washu Parking
Stretchmark Camouflage Highland Park
Chicago Neighborhoods: Lincoln Square & Ravenswood - Chicago Moms
Es.cvs.com/Otchs/Devoted
Gameplay Clarkston
Produzione mondiale di vino
Heska Ulite
The Wicked Lady | Rotten Tomatoes
Day Octopus | Hawaii Marine Life
Aquatic Pets And Reptiles Photos
Skylar Vox Bra Size
2024 Non-Homestead Millage - Clarkston Community Schools
DBZ Dokkan Battle Full-Power Tier List [All Cards Ranked]
St Maries Idaho Craigslist
H12 Weidian
Full Standard Operating Guideline Manual | Springfield, MO
Vegas7Games.com
Little Rock Skipthegames
Munis Self Service Brockton
Which Sentence is Punctuated Correctly?
Kroger Feed Login
Walgreens On Bingle And Long Point
Craigslist Fort Smith Ar Personals
Speechwire Login
Mjc Financial Aid Phone Number
Gesichtspflege & Gesichtscreme
Solo Player Level 2K23
Sinai Sdn 2023
Rugged Gentleman Barber Shop Martinsburg Wv
Loopnet Properties For Sale
Baddies Only .Tv
Newcardapply Com 21961
Arcadia Lesson Plan | Day 4: Crossword Puzzle | GradeSaver
Sams La Habra Gas Price
Skill Boss Guru
Myql Loan Login
Ise-Vm-K9 Eol
Pp503063
Td Ameritrade Learning Center
Red Dead Redemption 2 Legendary Fish Locations Guide (“A Fisher of Fish”)
Infinite Campus Farmingdale
Simnet Jwu
Chathuram Movie Download
Pa Legion Baseball
Ds Cuts Saugus
552 Bus Schedule To Atlantic City
Marine Forecast Sandy Hook To Manasquan Inlet
Phunextra
Gelato 47 Allbud
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 6027

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.