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
Startup Funding - The Dos and Don'ts of Approaching an Investor
Forex Diamond EA Review
The Tribes and Castes of the Central Provinces of India, Volume 3
Cpmc Mission Bernal Campus & Orthopedic Institute Photos
7 Verification of Employment Letter Templates - HR University
Urist Mcenforcer
Shoe Game Lit Svg
Craigslist Niles Ohio
Booknet.com Contract Marriage 2
Ross Dress For Less Hiring Near Me
Zitobox 5000 Free Coins 2023
Sams Gas Price Fairview Heights Il
Mephisto Summoners War
Colts seventh rotation of thin secondary raises concerns on roster evaluation
Los Angeles Craigs List
Springfield Mo Craiglist
978-0137606801
State HOF Adds 25 More Players
Rufus Benton "Bent" Moulds Jr. Obituary 2024 - Webb & Stephens Funeral Homes
Cardaras Funeral Homes
Vera Bradley Factory Outlet Sunbury Products
Dexter Gomovies
Keshi with Mac Ayres and Starfall (Rescheduled from 11/1/2024) (POSTPONED) Tickets Thu, Nov 1, 2029 8:00 pm at Pechanga Arena - San Diego in San Diego, CA
Laveen Modern Dentistry And Orthodontics Laveen Village Az
Star News Mugshots
6465319333
Wega Kit Filtros Fiat Cronos Argo 1.8 E-torq + Aceite 5w30 5l
LEGO Star Wars: Rebuild the Galaxy Review - Latest Animated Special Brings Loads of Fun With An Emotional Twist
Hypixel Skyblock Dyes
Robot or human?
The Mad Merchant Wow
Synchrony Manage Account
Craigslist Pets Huntsville Alabama
Collier Urgent Care Park Shore
Ursula Creed Datasheet
Ise-Vm-K9 Eol
Vocabulary Workshop Level B Unit 13 Choosing The Right Word
Craigslist En Brownsville Texas
Casamba Mobile Login
Author's Purpose And Viewpoint In The Dark Game Part 3
Tedit Calamity
Deepwoken: How To Unlock All Fighting Styles Guide - Item Level Gaming
Woody Folsom Overflow Inventory
The Sports Academy - 101 Glenwest Drive, Glen Carbon, Illinois 62034 - Guide
Plasma Donation Greensburg Pa
Tyrone Unblocked Games Bitlife
Congressional hopeful Aisha Mills sees district as an economical model
Mike De Beer Twitter
Bloons Tower Defense 1 Unblocked
Emmi-Sellers
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.