*args, **kwargs in python

Humble Devassy Chirammal Forums Python Programming *args, **kwargs in python

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #2082 Reply
    Humble
    Keymaster

    why are these used for ? its used for passing variable number of arguments , by variable I mean “you are or the function definition does not know how many arguments are going to get passed” .. *args is used to send a non-keyworded variable length argument list to the function.

    >>> def var_args(*Args):
    ...     for arg in Args:
    ...             print arg
    ... 
    >>> var_args(1,34,"hum","asd")
    1
    34
    hum
    asd
    >>> 
    
    
    oh , Did I make a mistake by mentioning *Args in function defnintion instead of *args.. No, I didnt.. That said, the keyword is not important . What is important is that *.
    
    **kwargs helps you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function.
    
    
    >>> def var_args1(**wargs):
    ...     for k,v in wargs.items():
    ...             print k,v
    ... 
    >>> var_args1(name="2",hobby="cricket")
    hobby cricket
    name 2
    >>> 
    
    
    
    So wargs ( again I used a different name than kwargs ) got it as dictionary.. 
    
    
    >>> k={"name1":"humble", "dist":"asdom"}
    >>> var_args1(**k)
    dist asdom
    name1 humble
    >>> 
    
    
    
    
    [ Will update the content some more]
    
Viewing 1 post (of 1 total)
Reply To: *args, **kwargs in python
Your information: