SoFunction
Updated on 2025-03-10

Detailed explanation of * and ** usage examples in python

Preface

People who have studied C/C++ always use python***It is considered related to pointers, but there are actually no pointers in python. In general, in python*and**There are four functions ofNumerical calculationSequence unpackingFunction declaration is used as function parameterWhen calling a function, it is used as a function parameter.. Note that there is no sequence unpacking**usage

The following content is based on Python 3.13.

1. * and ** usage

* Usage:

1. Use as an operator symbol multiplication
2. When a function is defined, *args is used to accept any number of positional parameters and pass them as a tuple to the function body.
3. When calling a function, * can be used to unpack an iterable object, splitting the iterable object into a separate positional parameter.
4. Use * before iterable objects such as lists, tuples, etc., which can be unpacked into separate elements to build new lists or tuples.

** Usage:

1. When defining a function, **kwargs is used to accept any number of keyword parameters and pass them as a dictionary to the function body.
2. When calling a function, ** can be used to unpack the dictionary and pass the key-value pairs in the dictionary as keyword parameters to the function.
3. Use ** before the dictionary, which can be unpacked into separate key-value pairs for building a new dictionary.

About positional parameters(*args) and keyword parameters (**kwargs) can refer to another blog post "Detailed explanation of Python parameters, python parameter types, positional parameters, default parameters, optional parameters

2. Use examples

2.1. Numerical operation

2.1.1. Usage of *

*Represents multiplication, which can be used for multiplication operations between two numbers, or for repeating a sequence or string operation. Here are some examples:

1. Example of number multiplication:

a = 2 * 3
print(a)  # Output: 6

2. Sequence duplication example:

b = [1, 2, 3] * 2
print(b)  # Output: [1, 2, 3, 1, 2, 3]

3. Example of string duplication:

c = "Hello " * 3
print(c)  # Output: "Hello Hello Hello Hello"

2.1.2. Usage of **

**Represents the multiplier, used to calculate the power of a number. Here is an example:

d = 2 ** 3
print(d)  # Output: 8

2.2. Use in iterator

  • *For sequence (list, tuple) unpacking, sequence unpacking**

2.2.1. * Unpacking list, tuple

  • When the iterator is unpacked, * is used to unpack the remaining elements, assigning them to a variable. This variable can be a list or tuple, which will receive all remaining elements.
  • *The usage of the function is usually very useful when multiple values ​​are returned.

1. Add a list or tuple variable before it*, means splitting a list or tuple element into a single value

#Split Listlist = [1, 2, 3]
print(*list)   #Output: 1 2 3 # is equivalent to print(1,2,3)
#Split Tupleslist = ('a', 'b', 'c')
print(*list)  #Output: a b c # is equivalent to print(1,2,3)

2. When unpacking the iterator,*Used to unpack the remaining elements and assign them to a variable.

# Unpacking listlist = [1, 2, 3, 4, 5]

a, *b, c = list

print(a)  # Output: 1print(b)  # Output: [2, 3, 4]print(c)  # Output: 5
# Unpack tupleslist = (1, 2, 3, 4, 5)

a, *b, c = list

print(a)  # Output: 1print(b)  # Output: [2, 3, 4]print(c)  # Output: 5

In the above example,*bIndicates unpacking the remaining elements and assigning them to variablesb. in this case,bWill be a list containing all elements except the first and last elements.

2.3. Extended sequence

2.3.1. Extended list

*Can be used to extend a list, splitting elements in one list and passing them to another list.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
(list2)
print(list1)  # Output [1, 2, 3, 4, 5, 6]
# Use * to extend the listlist1 = [1, 2, 3]
list2 = [4, 5, 6]
list1 = [*list1, *list2]
print(list1)  # Output [1, 2, 3, 4, 5, 6]
b = [1, 2, 3] * 2
print(b)  # Output: [1, 2, 3, 1, 2, 3]

Note: When using * to extend the list, if there are elements that are duplicated, the duplicate elements will not be deduplicated.

2.3.2. Extended Dictionary

**Can be used to extend a dictionary, splitting key-value pairs in one dictionary and passing them to another dictionary.

dict1 = {"name": "Zhang San", "age": 22}
dict2 = {"sex": "male"}
(dict2)
print(dict1)
# Output: {'name': 'Zhang San', 'age': 22, 'sex': 'Male'}
# Use ** to extend the dictionarydict1 = {"name": "Zhang San", "age": 22}
dict2 = {"sex": "male"}
dict1 = {**dict1, **dict2}
print(dict1)
# Output: {'name': 'Zhang San', 'age': 22, 'sex': 'Male'}

Notice:use**When expanding a dictionary, if the dictionary’s keys are repeated, the following will overwrite the previous one.

# Use ** to extend the dictionarydict1 = {"name": "Zhang San", "age": 22}
dict2 = {"name": "Li Si"}
dict1 = {**dict1, **dict2} #If the dictionary keys are repeated, the following ones cover the previous onesprint(dict1)
# Output: {'name': 'Li Si', 'age': 22}

2.4. Use in function definitions and calls

2.4.1. Usage of *

  • In the function definition,*Indicates mandatory keyword parameters,*The following parameters must be keyword parameters.

For compulsory keyword parameters, please refer to "Detailed explanation of Python parameters, python parameter types, positional parameters, default parameters, optional parameters

For example:

def my_function(a, b, *, c):
    print(a, b, c)

my_function(1, 2, c=3)  # Output: 1 2 3

In the example, a and b are positional parameters only, specified in order; c is keyword parameters and must be written in the form of key=value.

  • In a function definition, *args means accepting any number of positional parameters and passing them to the function as a tuple.
def my_function(*args):
	print(args)

my_function(1,2,3)  # Output: (1,2,3)

You can find that *args will receive elements as tuples by default

# Use *args to accept any number of position parametersdef my_function(*args):
    for arg in args:
        print(arg)

my_function(1, 2, 3)  
# Output:1
2
3
  • In a function call, * is used to unpack a sequence, passing each element in the sequence to the function as a separate parameter.
# Use * unpacking sequence as function parameterdef my_function(a, b, c):
    print(a, b, c)

# Unpack the listmy_list = [1, 2, 3]
my_function(*my_list)  # Output: 1 2 3
# Unpack tuplesmy_list = (1, 2, 3)
my_function(*my_list)  # Output: 1 2 3

2.4.2. Usage of **

  • In function definition, **kwargs means accepting any number of keyword parameters and placing themPass as a dictionary to a function
# Use **kwargs to accept any number of keyword parametersdef person(**kwargs):
    print(kwargs)
    for key, value in ():
        print(key, value)

person(name="Zhang San", age=25)  

#Execution results{'name': 'Zhang San', 'age': 25}
name Zhang San
age 25

The above example can be seen

  • In a function call,**Used to unpack the dictionary, passing each key-value pair in the dictionary to the function as a keyword argument.
# Use ** to unpack dictionary as function parameterdef person(name, age):
    print(name, age)

my_dict = {"name": "Zhang San", "age": 25}
person(**my_dict)  # Output: Zhang San 25
above**The writing method is equivalent to
person(name= "Zhang San", age= 25)  # Output: Zhang San 25

Summarize

This is the end of this article about the detailed explanation of * and ** usage examples in python. For more related content on * and ** usage in python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!