How to pass multiple arguments into function

I'm trying to parse a json file, Suppose the function that is called takes in the json path from a variable called section1

def traverseJson(arg1):
    #do stuff

section1 = json["section"]["section"][1]

To call the function I'd run:


How would I then pass in multiple arguments into the function? e.g

section2 = json["section"]["subsection"][0]
section3 = json["section"]["subsection"][0]

A solution which does not predefine the number of arguments will be more suitable as the number of arguments can vary.

3 answers

  • answered 2017-06-17 19:20 PatNowak

    You can pass this kind of arguments as an array or as a dictionary (keyword map).

    To pass as an array use * operator, to pass as a hash, use ** operator.


    def function(first_arg, *args, **kwargs): 
      # something

    Read more here and here.

  • answered 2017-06-17 19:20 Linch

    You can use *args syntax:

    def traverse(*args):
        for arg in args:
            # logic

    UPDATE: Usage

    section1 = ...
    section2 = ...
    traverse(section1, section2)
    # or
    sections = [..., ...]

  • answered 2017-06-17 19:20 dwmyfriend

    If you know the maximum number of args an un-pythonic way of doing it would be

    def traverseJson(arg1=0, arg2=0, arg3=0, arg4=0):

    If four arguments aren't given it just assigns 0 to the remaining variables.

    However, I would recommend passing the arguments as a list. e.g.

    def traverseJson(arg1) :
        for i in arg1:
            #do stuff
    traverseJson([section1, section2, section3])

    Hope this helps