Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array/list into a Python function

I've been looking at passing arrays, or lists, as Python tends to call them, into a function.

I read something about using *args, such as:

def someFunc(*args)     for x in args         print x 

But not sure if this is right/wrong. Nothing seems to work as I want. I'm used to be able to pass arrays into PHP function with ease and this is confusing me. It also seems I can't do this:

def someFunc(*args, someString) 

As it throws up an error.

I think I've just got myself completely confused and looking for someone to clear it up for me.

like image 608
Jack Franklin Avatar asked Oct 18 '10 16:10

Jack Franklin


People also ask

Can I pass an array to a function in Python?

In Python, any type of data can be passed as an argument like string, list, array, dictionary, etc to a function.

How do you pass a list to a function in Python?

Use the * Operator in Python The * operator can unpack the given list into separate elements that can later be tackled as individual variables and passed as an argument to the function.

Can you pass an entire array to a function?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

How do you pass a list by reference in Python?

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.


1 Answers

When you define your function using this syntax:

def someFunc(*args):     for x in args         print x 

You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:

def someFunc(myList = [], *args):     for x in myList:         print x 

Then you can call it with this:

items = [1,2,3,4,5]  someFunc(items) 

You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:

def someFunc(arg1, arg2, arg3, *args, **kwargs):     for x in args         print x 

Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.

like image 176
g.d.d.c Avatar answered Sep 22 '22 21:09

g.d.d.c