SoFunction
Updated on 2024-12-10

Meaning and description of python variables preceded by a star (*)

Meaning of python variables preceded by a star (*)

1. When constructing a function, add * in front of the variable to represent receiving parameters in the form of tuples.

def func(*args)

2, used to construct arrays, can be seen as a generator, and constantly will be input one by one to generate things out.

importation(1,2),Then, in turn, it produces1,2
importation[1,2],Then, in turn, it produces1.2
v1 = (1,2)

v2 = [3,4]

([0,*v1])

([*v2])

([0,*v1,*v2]) 

3, constructor when the form of the parameter before adding two **, on behalf of receiving the dictionary form of the parameters.

def func(**args)

Adding an asterisk (*) to parameters in Python methods

Simply put, an asterisk represents an "unpacking" operation.

This is illustrated below using examples:

Use of single asterisks

arr = [0, 1, 2, 3] # (0, 1, 2, 3) results are consistent
def count(*s):
    print(s)
count(*arr)
# in the end:(0, 1, 2, 3)

A single asterisk treats the parameter s as atupletype, care is needed when performing the operation.

arr = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
def count(*s):
    print(s)
count(*arr)
# in the end:('a', 'b', 'c', 'd')

When we pass in an argument that is originally a dictionary type, the argument s represents the key of the dictionary.

Use of double asterisks

arr = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
def count(**s):
    print(s)
count(**arr)
# in the end:{'a': 0, 'b': 1, 'c': 2, 'd': 3}

A double asterisk treats the argument s as adictionariesThe following are some examples of the types of dictionaries that can be used.

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.