def print_lists(*lists): print("There are ", len(lists), " lists.") for l in lists: print(l) print_lists([1, 2, 3], [4, 5, 6], [7, 8, 9])
Here, we are passing an arbitrary number of Python lists as arguments. The function print_lists() prints the lists one by one. Also, we are using len(lists) function to print the number of lists passed as arguments. The above program will print the following output:
There are 3 lists. [1, 2, 3] [4, 5, 6] [7, 8, 9]
How to pass arbitrary keyword arguments to a Python function?
Let’s say there is a function print_user_information() that prints information about a user. Now, we can pass various information about the user, e.g. the user’s firstname, lastname, contact number, email address, etc. The function should be able to print all the information correctly.
Now, we can pass arbitrary arguments to a function. But, here, the function should be able to know whether a passed argument is the user’s first name, lastname, contact number or email address. In other words, we need to pass an arbitrary number of keyword arguments to the function. In such scenarios, we use arbitrary keyword arguments in Python.
def print_user_information(**user): for key, value in user.items(): print("%s = %s" % (key, value)) print_user_information(first_name="Amit", last_name="Sen", contact_number="1234", email_address="[email protected]")
The function will print the following output:
first_name = Amit last_name = Sen contact_number = 1234 email_address = [email protected]
So, as we can see, the function not only accepts an arbitrary number of arguments, it also gets the names of the variables.
Please note that the passed keyword arguments are stored in “key: value” format in the parameter. So, we can iterate through …






0 Comments