In Python, the * and ** symbols are used to denote special types of arguments when defining a function.
The * symbol is used to denote a variable-length argument list. This allows a function to accept any number of arguments, including zero. Here is an example:
def my_function(*args): # args is a tuple that contains all of the arguments passed to the function for arg in args: print(arg) my_function(1, 2, 3) # Output: # 1 # 2 # 3
In this example, the * symbol is used to define a variable-length argument list named args. When the function is called, all of the arguments are collected into a tuple and assigned to args. This allows us to loop over the arguments and process them individually.
The ** symbol is similar to the * symbol, but it is used to denote a dictionary of keyword arguments. This allows a function to accept any number of named arguments, including zero. Here is an example:
def my_function(**kwargs): # kwargs is a dictionary that contains all of the keyword arguments passed to the function for key, value in kwargs.items(): print(f"{key}: {value}") my_function(arg1=1, arg2=2, arg3=3) # Output: # arg1: 1 # arg2: 2 # arg3: 3
def my_function(arg1, arg2, arg3): print(f"{arg1}, {arg2}, {arg3}") my_list = [1, 2, 3] my_function(*my_list) # Output: # 1, 2, 3 my_dict = {"arg1": 1, "arg2": 2, "arg3": 3} my_function(**my_dict) # Output: # 1, 2, 3
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.