The Wayback Machine - https://web.archive.org/web/20240705175850/https://www.geeksforgeeks.org/unpacking-arguments-in-python/
Open In App

Unpacking arguments in Python

Last Updated : 05 Sep, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

If you have used Python even for a few days now, you probably know about unpacking tuples. Well for starter, you can unpack tuples or lists to separate variables but that not it. There is a lot more to unpack in Python.

Unpacking without storing the values: You might encounter a situation where you might not need all the values from a tuple but you want to store only some of them. In that case, you can use an _ to ignore certain values. Now, let’s combine  it with the above * implementation

Example 1:

Python3




# unpacking python tuple using _ 
  
# first and last value will be ignored 
# and won't be stored second will be 
# assigned to b and remaining will be
# assigned to x 
_, b, *x, _ = ("I ", "love ", "Geeks ",
               "for ", "Geeks ", 3000) 
  
# print details 
print(b)
print(x) 


Output:

love 
['Geeks ', 'for ', 'Geeks ']

Explanation:

Notice here the first and last variables are set to underscore ( _ ). In python, underscore is used for ignoring values or throw away variables, which means that “I ” and 3000 won’t be stored.

Example 2:

Python3




# unpacking python tuple using _* 
  
# first second and last value will be stored
# remaining will be ignored by using *_
a, b, *_, c = ("I ", "love ", "Geeks ",
               "for ", "Geeks ", 3000) 
  
# print details 
print(a)
print(b) 
print(c)


Output:

I 
love 
3000

Explanation:

Notice here in a and b, the first and second values get assigned and in c, the last value gets assigned. So, what about the third, fourth, and fifth? Well, they simply get ignored because we have used *_. If we used * with a variable then all those would get into that variable as a list. Since, we have used _ instead of a variable, so the entire list of words gets ignored completely. 

Example 3: Well, the idea here is to create a function that will take in a list of numbers and return its sum, average, maximum, and minimum in the list. We will then reuse the function to get that we need for different use cases.

Python3




def arithmetic_operations(arr: list):
  MAX = max(arr)
  MIN = min(arr)
  SUM = sum(arr)
  AVG = SUM/len(arr)
    
  return (SUM, AVG, MAX, MIN)
  
if __name__ == '__main__':
  arr = [5, 8, 9, 12, 50, 3, 1]
    
  # for all data
  sum_arr, avg_arr, max_arr, min_arr = arithmetic_operations(arr)
  print("CASE 1 ", sum_arr, avg_arr, max_arr, min_arr)
    
  #for only avg and max
  _, avg_arr, max_arr, _ = arithmetic_operations(arr)
  print("CASE 2 ", avg_arr, max_arr)
    
  # for only sum and min
  sum_arr, *_, min_arr = arithmetic_operations(arr)
  print("CASE 3 ", sum_arr, min_arr)


Output:

CASE 1  88 12.571428571428571 50 1
CASE 2  12.571428571428571 50
CASE 3  88 1

The above code is for demonstrating how you can have one function returning multiple values but use only the ones necessary at a time without wasting memory.



Similar Reads

Packing and Unpacking Arguments in Python
We use two operators * (for tuples) and ** (for dictionaries). Background Consider a situation where we have a function that receives four arguments. We want to make a call to this function and we have a list of size 4 with us that has all arguments for the function. If we simply pass a list to the function, the call doesn't work. C/C++ Code # A Py
5 min read
Unpacking a Tuple in Python
Python Tuples In python tuples are used to store immutable objects. Python Tuples are very similar to lists except to some situations. Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of value
3 min read
Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers]. There is another method that uses command line arg
2 min read
Python | Passing dictionary as keyword arguments
Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it's values as argument values. Let's d
3 min read
Python: Passing Dictionary as Arguments to Function
A dictionary in Python is a collection of data which is unordered and mutable. Unlike, numeric indices used by lists, a dictionary uses the key as an index for a specific value. It can be used to store unrelated data types but data that is related as a real-world entity. The keys themselves are employed for using a specific value. Refer to the belo
2 min read
Tuple as function arguments in Python
Tuples have many applications in all the domains of Python programming. They are immutable and hence are important containers to ensure read-only access, or keeping elements persistent for more time. Usually, they can be used to pass to functions and can have different kinds of behavior. Different cases can arise. Case 1: fnc(a, b) - Sends a and b
2 min read
Python - pass multiple arguments to map function
The map() function is a built-in function in Python, which applies a given function to each item of iterable (like list, tuple etc.) and returns a list of results or map object. Syntax : map( function, iterable ) Parameters : function: The function which is going to execute for each iterableiterable: A sequence or collection of iterable objects whi
3 min read
Executing functions with multiple arguments at a terminal in Python
Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are: Using sys.argv Using getopt module/li> Using argparse module The Python sys module allows access to command-line argument
4 min read
How to handle invalid arguments with argparse in Python?
Argparse module provides facilities to improve the command-line interface. The methods associated with this module makes it easy to code for command-line interface programs as well as the interaction better. This module automatically generates help messages and raises an error when inappropriate arguments are passed. It even allows customizing the
4 min read
How to find the number of arguments in a Python function?
In this article, we are going to see how to count the number of arguments of a function in Python. We will use the special syntax called *args that is used in the function definition of python. Syntax *args allow us to pass a variable number of arguments to a function. We will use len() function or method in *args in order to count the number of ar
1 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg