Packing and Unpacking Arguments in Python
Last Updated :
18 Feb, 2025
Python provides the concept of packing and unpacking arguments, which allows us to handle variable-length arguments efficiently. This feature is useful when we don’t know beforehand how many arguments will be passed to a function.
Packing Arguments
Packing allows multiple values to be combined into a single parameter using * (for tuples/lists) and ** (for dictionaries).
- *args (Non-keyword arguments): Packs multiple positional arguments into a tuple.
- **kwargs (Keyword arguments): Packs multiple keyword arguments into a dictionary.
1. Packing with *args
The *
operator allows us to pass multiple arguments to a function and pack them into a tuple.
Example Code:
Python
def sample(*args):
print("Packed arguments:", args)
sample(1, 2, 3, 4, "geeks for geeks")
OutputPacked arguments: (1, 2, 3, 4, 'geeks for geeks')
Explanation:
- The function takes any number of arguments.
- The
*args
packs all arguments into a tuple.
2. Packing with **kwargs
** operator is used to collect multiple keyword arguments into a dictionary.
Code
Python
def sample(**kwargs):
print("Packed keyword arguments:", kwargs)
sample(name="Anaya", age=25, country="India")
OutputPacked keyword arguments: {'name': 'Anaya', 'age': 25, 'country': 'India'}
Explanation:
**kwargs
collects keyword arguments as a dictionary.- Each key-value pair is stored in
kwargs
.
Unpacking Arguments
Unpacking allows values from an iterable (list, tuple, or dictionary) to be passed as separate arguments to a function.
1. Unpacking a List/Tuple with *
We use * to unpack elements from a list/tuple.
Example
Python
def addition(a, b, c):
return a + b + c
num = (1, 5, 10)
result = addition(*num)
print("Sum:", result)
Explanation: *numbers
unpacks numbers
into a, b, c
.
2. Unpacking a Dictionary with **
We use **
to unpack key-value pairs from a dictionary.
Example
Python
def info(name, age, country):
print(f"Name: {name}, Age: {age}, Country: {country}")
data = {"name": "geeks for geeks", "age": 30, "country": "India"}
info(**data)
OutputName: geeks for geeks, Age: 30, Country: India
Explanation: **data unpack dictionary values and assign them to parameters.
Packing and Unpacking Together
We can use Packing and Unpacking in same function.
Example
Python
def together(*args, **kwargs):
print("Positional:", args)
print("Keyword arguments:", kwargs)
together(1, 2, 3, name="geeks for geeks", age=30)
OutputPositional: (1, 2, 3)
Keyword arguments: {'name': 'geeks for geeks', 'age': 30}
Explanation:
*args
collects (1, 2, 3)
as a tuple.**kwargs
collects name="geeks for geeks"
and age=30
into a dictionary.
Difference between Packing and Unpacking
Features | Packing | Unpacking |
---|
Definition | Collects multiple values into a single variable (tuple, list, or dictionary). | Extracts values from a collection (tuple, list, or dictionary) into individual variables. |
---|
Operator Used | * (for tuples/lists), ** (for dictionaries).
| * (for lists/tuples), ** (for dictionaries).
|
---|
Purpose | Allows functions to accept a variable number of arguments. | Allows passing values dynamically to functions or variables. |
---|
Data Structure | Combine multiple values into a single entity (tuple or dictionary). | Extracts multiple values from a single entity into separate variables. |
---|
Example in function definition | def func(*args): (packs multiple positional arguments into a tuple) def func(**kwargs): (packs multiple keyword arguments into a dictionary)
| func(*list_var) (unpacks elements from a list/tuple) func(**dict_var) (unpacks key-value pairs from a dictionary)
|
---|
Example inf unction call | func(1, 2, 3, 4) → Packs (1, 2, 3, 4) into args .
| func(*[1, 2, 3, 4]) → Unpacks [1, 2, 3, 4] as separate arguments.
|
---|
Storage Format | Tuple (*args ) or Dictionary (**kwargs ). | Individual variables or function arguments. |
---|
Similar Reads
Loops in Python - For, While and Nested Loops Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). Additionally, Nested Loops allow looping within loops for more complex tasks. While all the ways provide similar basic functionality, they differ in th
9 min read
Loops and Control Statements (continue, break and pass) in Python Python supports two types of loops: for loops and while loops. Alongside these loops, Python provides control statements like continue, break, and pass to manage the flow of the loops efficiently. This article will explore these concepts in detail.Table of Contentfor Loopswhile LoopsControl Statemen
2 min read
range() vs xrange() in Python The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range(
4 min read
Using Else Conditional Statement With For loop in Python Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while
2 min read
Iterators in Python An iterator in Python is an object that holds a sequence of values and provide sequential traversal through a collection of items such as lists, tuples and dictionaries. . The Python iterators object is initialized using the iter() method. It uses the next() method for iteration.__iter__(): __iter__
3 min read
Iterator Functions in Python | Set 1 Perquisite: Iterators in PythonPython in its definition also allows some interesting and useful iterator functions for efficient looping and making execution of the code faster. There are many build-in iterators in the module "itertools". This module implements a number of iterator building blocks.
4 min read
Converting an object into an iterator In Python, we often need to make objects iterable, allowing them to be looped over like lists or other collections. Instead of using complex generator loops, Python provides the __iter__() and __next__() methods to simplify this process.Iterator Protocol:__iter__(): Returns the iterator object itsel
5 min read
Python | Difference between iterable and iterator Iterable is an object, that one can iterate over. It generates an Iterator when passed to iter() method. An iterator is an object, which is used to iterate over an iterable object using the __next__() method. Iterators have the __next__() method, which returns the next item of the object. Note: Ever
3 min read
When to use yield instead of return in Python? The yield statement suspends a function's execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off. When the function resumes, it continues execution immediately after the last yield run. This allows its code to produce a series of v
2 min read
Generators in Python Python generator functions are a powerful tool for creating iterators. In this article, we will discuss how the generator function works in Python.Generator Function in PythonA generator function is a special type of function that returns an iterator object. Instead of using return to send back a si
5 min read