首页 > 编程语言 >Unpack and pass list, tuple, dict to function arguments in Python

Unpack and pass list, tuple, dict to function arguments in Python

时间:2023-03-13 21:46:52浏览次数:57  
标签:function tuple Python arg1 arg2 arg3 two three func

reprinted: note.nkmk.me-Unpack and pass list, tuple, dict to function arguments in Python

In Python, you can unpack list, tuple, dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.

This article describes the following contents.

  • Unpack list and tuple with *
    • With default arguments
    • With variable-length arguments
  • Unpack dict (dictionary) with **
    • With default arguments
    • With variable-length arguments

Note that if list, tuple, or dict is specified as an argument without * or **, it is not be unpacked and passed to the function as is.

See the following articles for basic usage of functions in Python, default arguments, and variable-length arguments with * and ** when defining functions.

Unpack list and tuple with *

When specifying a list or tuple with * as an argument, it is unpacked, and each element is passed to each argument.

def func(arg1, arg2, arg3):
    print('arg1 =', arg1)
    print('arg2 =', arg2)
    print('arg3 =', arg3)

l = ['one', 'two', 'three']

func(*l)
# arg1 = one
# arg2 = two
# arg3 = three

func(*['one', 'two', 'three'])
# arg1 = one
# arg2 = two
# arg3 = three

t = ('one', 'two', 'three')

func(*t)
# arg1 = one
# arg2 = two
# arg3 = three

func(*('one', 'two', 'three'))
# arg1 = one
# arg2 = two
# arg3 = three

Lists are used in the following sample code, but the same applies to tuples.

If the number of elements does not match the number of arguments, TypeError raises.

# func(*['one', 'two'])
# TypeError: func() missing 1 required positional argument: 'arg3'

# func(*['one', 'two', 'three', 'four'])
# TypeError: func() takes 3 positional arguments but 4 were given

With default arguments

If the function has default arguments, the default arguments are used if the number of elements is insufficient. If there are many elements, TypeError raises.

def func_default(arg1=1, arg2=2, arg3=3):
    print('arg1 =', arg1)
    print('arg2 =', arg2)
    print('arg3 =', arg3)

func_default(*['one', 'two'])
# arg1 = one
# arg2 = two
# arg3 = 3

func_default(*['one'])
# arg1 = one
# arg2 = 2
# arg3 = 3

# func_default(*['one', 'two', 'three', 'four'])
# TypeError: func_default() takes from 0 to 3 positional arguments but 4 were given

With variable-length arguments

If the function has a variable-length argument (*args), all elements after the positional argument are passed to the variable-length argument.

def func_args(arg1, *args):
    print('arg1 =', arg1)
    print('args =', args)

func_args(*['one', 'two'])
# arg1 = one
# args = ('two',)

func_args(*['one', 'two', 'three'])
# arg1 = one
# args = ('two', 'three')

func_args(*['one', 'two', 'three', 'four'])
# arg1 = one
# args = ('two', 'three', 'four')

Unpack dict (dictionary) with **

By adding ** to dict (dictionary) and specifying it as an argument, its keys and values are treated as names and values of arguments. Each element is passed as keyword arguments.

def func(arg1, arg2, arg3):
    print('arg1 =', arg1)
    print('arg2 =', arg2)
    print('arg3 =', arg3)

d = {'arg1': 'one', 'arg2': 'two', 'arg3': 'three'}

func(**d)
# arg1 = one
# arg2 = two
# arg3 = three

func(**{'arg1': 'one', 'arg2': 'two', 'arg3': 'three'})
# arg1 = one
# arg2 = two
# arg3 = three

If there are not enough keys or keys that do not match the argument names, TypeError raises.

# func(**{'arg1': 'one', 'arg2': 'two'})
# TypeError: func() missing 1 required positional argument: 'arg3'

# func(**{'arg1': 'one', 'arg2': 'two', 'arg3': 'three', 'arg4': 'four'})
# TypeError: func() got an unexpected keyword argument 'arg4'

With default arguments

If the function has default arguments, only the value of the argument name matching the dictionary key is updated.

If a key does not match the argument name, TypeError is raised.

def func_default(arg1=1, arg2=2, arg3=3):
    print('arg1 =', arg1)
    print('arg2 =', arg2)
    print('arg3 =', arg3)

func_default(**{'arg1': 'one'})
# arg1 = one
# arg2 = 2
# arg3 = 3

func_default(**{'arg2': 'two', 'arg3': 'three'})
# arg1 = 1
# arg2 = two
# arg3 = three

# func_default(**{'arg1': 'one', 'arg4': 'four'})
# TypeError: func_default() got an unexpected keyword argument 'arg4'

With variable-length arguments

If the function has a variable-length argument (**kwargs), all elements with keys that do not match the argument name are passed to the variable-length argument.

def func_kwargs(arg1, **kwargs):
    print('arg1 =', arg1)
    print('kwargs =', kwargs)

func_kwargs(**{'arg1': 'one', 'arg2': 'two', 'arg3': 'three'})
# arg1 = one
# kwargs = {'arg2': 'two', 'arg3': 'three'}

func_kwargs(**{'arg1': 'one', 'arg2': 'two', 'arg3': 'three', 'arg4': 'four'})
# arg1 = one
# kwargs = {'arg2': 'two', 'arg3': 'three', 'arg4': 'four'}

func_kwargs(**{'arg1': 'one', 'arg3': 'three'})
# arg1 = one
# kwargs = {'arg3': 'three'}

标签:function,tuple,Python,arg1,arg2,arg3,two,three,func
From: https://www.cnblogs.com/lfri/p/17213001.html

相关文章

  • python
    1ans1=0.1+0.22print(f'0.1+0.2={ans1}')34importdecimal56ans2=decimal.Decimal('0.1')+decimal.Decimal('0.2')7print(f'0.1+0.2={ans2}')ViewCode......
  • python - ddddocr验证码识别
    1.ddddocr安装建议使用国内镜像安装pip3installddddocr-ihttps://pypi.tuna.tsinghua.edu.cn/simple2.图片验证码importddddocrocr=ddddocr.DdddOcr(show_a......
  • python数据分析
    importmatplotlib.pyplotaspltimportpandasaspddatafile='air_data.csv'resultfile='explore.csv'data=pd.read_csv(datafile,encoding='utf-8')explore=da......
  • python中的文件处理模块
    4种读法:如果文件很小,read()一次性读取最方便;如果不能确定文件大小,反复调用read(size)比较保险;如果是配置文件,调用readlines()最方便:#read():将文件中内容全部取出来#re......
  • 3.13python笔记
    1.print(str[0:-1])如上图所示,str[0:-1]为切片,意思是从前面开始截取到后面-1为止,所以输出第一个到倒数第二个的所有字符str="abcdef"print(str[0:-1])输出:abcde1232.pr......
  • Python字典生成式
    一、字典生成式print({i:i**2foriinrange(10)})输出{0:0,1:1,2:4,3:9,4:16,5:25,6:36,7:49,8:64,9:81}二、zip()方法keys=['name','age......
  • List comprehensions in Python
    Reprintedfrom:note.nkmk.me-ListcomprehensionsinPythonInPython,youcancreateanewlistusinglistcomprehensions.It'ssimplerthanusingtheforloop......
  • python中os模块
    1.os.name   #  获取操作系统类型,如果是posix,说明系统是Linux、Unix或MacOSX,如果是nt,就是Windows系统2.os.uname #  要获取详细的系统信息,可以调用uname()......
  • python85 路飞项目 文件存储、搜索导航栏、搜索接口、搜索页面、支付宝支付介绍、支
    文件存储#视频文件,存储到某个位置,如果放在自己服务器上放在项目的media文件夹服务器上线后,用户既要访问接口,又要看视频,都是一个域名和端口分开:文件单......
  • Python Yolo V8 训练自己的数据集
    前期准备工作需要使用到的库,需要训练的素材一份图片或者视频importultralytics#YoloV8本体importlableimg#图片标注工具接着新建一份工作目录如下---data......