Open In App

Unpacking arguments in Python

Last Updated : 05 Sep, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. [GFGTABS] Python
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
Pass function and arguments from node.js to Python
Prerequisites: How to run python scripts in node.js using the child_process module. In this article, we are going to learn how to pass functions and arguments from node.js to Python using child_process. Although Node.js is one of the most widely used web development frameworks, it lacks machine learning, deep learning, and artificial intelligence l
4 min read
Pass Arguments to the Metaclass from the Class in Python
Metaclasses in Python provide a powerful way to control the creation and behavior of classes. They act as the "class of a class" and allow you to customize class creation and behavior at a higher level. One interesting aspect of metaclasses is the ability to pass arguments from a class to its metaclass during the class definition. What is a Metacla
3 min read
Command Line Arguments in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are:  Using sys.argvUsing getopt moduleUsing argparse moduleUsing sys.argvThe sys module provides functions and
5 min read
Default arguments in Python
Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value. Default Arguments: Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is
7 min read
Deep dive into Parameters and Arguments in Python
There is always a little confusion among budding developers between a parameter and an argument, this article focuses to clarify the difference between them and help you to use them effectively. Parameters:A parameter is the variable defined within the parentheses during function definition. Simply they are written when we declare a function. Examp
3 min read
How to Print Multiple Arguments in Python?
An argument is a value that is passed within a function when it is called.They are independent items, or variables, that contain data or codes. During the time of call each argument is always assigned to the parameter in the function definition. Example: Simple argument [GFGTABS] Python def GFG(name, num): print("Hello from ", name +
3 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
3 min read
How to bind arguments to given values in Python functions?
In Python, binding arguments to specific values can be a powerful tool, allowing you to set default values for function parameters, create specialized versions of functions, or partially apply a function to a set of arguments. This technique is commonly known as "partial function application" and can be achieved using Python's functools.partial as
3 min read
Core arguments in serializer fields - Django REST Framework
Serializer fields in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields. In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. This article revolves around various arguments that serializer
6 min read
Functions that accept variable length key value pair as arguments
To pass a variable-length key-value pair as an argument to a function, Python provides a feature called **kwargs.kwargs stands for Keyword arguments. It proves to be an efficient solution when one wants to deal with named arguments in their function. Syntax: def functionName(**anything): statement(s) Note: adding '**' to any term makes it a kwargs
2 min read
How to Pass Arguments to Tkinter Button Command?
When a user hits the button on the Tkinter Button widget, the command option is activated. In some situations, it's necessary to supply parameters to the connected command function. In this case, the procedures for both approaches are identical; the only thing that has to vary is the order in which you use them. Method 1: Pass Arguments to Tkinter
2 min read
How to pass arguments to shell script in crontab ?
In this article, we will discuss how to schedule shell scripts in crontab and to pass necessary parameters as well. First, let's create a simple script that we will be scheduled to run every 2 minutes. The below is a simple script that calculates the sum of all parameters passed and prints them to STDOUT along with the time the script was run. #! /
2 min read
Passing URL Arguments in Flask
In this article, we will cover how to Pass URL Arguments in Flask using Python. URL converters in Flask are mentioned in angular brackets (<>). These unique converters are designed to let us generate extremely dynamic URLs, where a part of the URL is regarded as a variable. For that we have created three different endpoints to understand thre
4 min read
How to pass multiple arguments to function ?
A Routine is a named group of instructions performing some tasks. A routine can always be invoked as well as called multiple times as required in a given program.  When the routine stops, the execution immediately returns to the stage from which the routine was called. Such routines may be predefined in the programming language or designed or imple
5 min read
Get the number of Explicit Arguments in the Init of a Class
In Python, the __init__ method is used for initializing a newly created object. It typically contains parameters that set the initial state of an object. To count the number of explicit arguments in the __init__ method of a class, we can use the inspect module from Python's standard library. In this article, we will see how we can get the number of
3 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Article Tags :
Practice Tags :