Python's *args and **kwargs

Source: Internet
Author: User

1. *args allows you to pass a variable number of parameter lists (tuples) of a non-key-value pair to a function.

>>>defAdd (*args): ...returnsum (args) ...>>> Add (1,2,3,4)10>>> A = (1,2,3,4)>>> Add (a)#error, equivalent to sum (((1,2,3,4),), adding tuple a to 0Traceback (most recent): File"<stdin>", Line 1,inch<module>File"<stdin>", Line 2,inchaddtypeerror:unsupported operand type (s) for+:'int'  and 'tuple'>>> Add (*a)10>>> sum ((1,2,3,4) ,) Traceback (most recent): File"<stdin>", Line 1,inch<module>typeerror:unsupported operand type (s) for+:'int'  and 'tuple'

2. **kwargs allows you to pass a variable number of parameter dictionaries for a key-value pair to a function.

def Add (* *Kwargs): ...      return sum (kwargs.values ()) ... >>> Add (a=1,b=2,c=3)6

Comprehensive:

>>>defF (arg,*args,**Kwargs): ...Print(ARG) ...Print(args) ...Print(Kwargs) ...>>> f (1,* (1,2,3,4), **{"a": 1,"b": 2,"C": 3})1(1, 2, 3, 4){'b': 2,'C': 3,'a': 1}>>> F (1,1,2,3,4,a=1,b=2,c=3) # As with the above effect 

When called

deffunc (a,b,c,d):Print(a,b,c,d) args= (1,2,3,4) func (*args)1,2,3,4deffunc (a,b,c,d):Print(a,b,c,d) Kargs= {'a': 1,'b': 2,'C': 3,'D': 4}func (**Kargs)1,2,3,4

Python's *args and **kwargs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.