Python function list variable

Declaring a python function with an array parameters and passing an array argument to the function call?

I am a complete newbie to python and attempting to pass an array as an argument to a python function that declares a list/array as the parameter. I am sure I am declaring it wrong, here goes:

def dosomething(listparam): #do something here dosomething(listargument) 

Could you provide some more context, maybe the actual code that fails? (If possible, make it a good example). And what do you mean by declaring?

oh yes it is absolutely my bad. i was doing this: for x in range(len(list)): print x; instead of print list[x] . thanks all!

This looks correct; are you getting a specific error message? Perhaps you have not declared / put something inside listargument?

3 Answers 3

What you have is on the right track.

def dosomething( thelist ): for element in thelist: print element dosomething( ['1','2','3'] ) alist = ['red','green','blue'] dosomething( alist ) 

A couple of things to note given your comment above: unlike in C-family languages, you often don’t need to bother with tracking the index while iterating over a list, unless the index itself is important. If you really do need the index, though, you can use enumerate(list) to get index,element pairs, rather than doing the x in range(len(thelist)) dance.

Читайте также:  Все стили шрифтов css

Maybe you want to unpack elements of an array, I don’t know if I got it, but below an example:

def my_func(*args): for a in args: print(a) my_func(*[1,2,3,4]) my_list = ['a','b','c'] my_func(*my_list) 

I guess I’m unclear about what the OP was really asking for. Do you want to pass the whole array/list and operate on it inside the function? Or do you want the same thing done on every value/item in the array/list. If the latter is what you wish I have found a method which works well.

I’m more familiar with programming languages such as Fortran and C, in which you can define elemental functions which operate on each element inside an array. I finally tracked down the python equivalent to this and thought I would repost the solution here. The key is to ‘vectorize’ the function. Here is an example:

def myfunc(a,b): if (a>b): return a else: return b vecfunc = np.vectorize(myfunc) result=vecfunc([[1,2,3],[5,6,9]],[7,4,5]) print(result) 

Источник

Python — use a list with variable names as input for a function

How can I use the string variable names as variables in a function? Example: Use the variable in the list for:

x = np.concatenate((var1, var2, var3), axis = 1) 

2 Answers 2

def some_function(**kwargs): var1 = kwargs.get('var1') var2 = kwargs.get('var2') var3 = kwargs.get('var3') s = ['var1', 'var2', 'var3'] vals = ["someval1", "someval2", "someval3"] some_function(**) 

Now, in the function some_function , var1 , var2 , and var3 store «someval1» , «someval2» , «someval3»

To achieve this you will need to use * or ** operator

my_func(*[a, b]) # equals to my_func(a, b) 

And the same works with dicts

my_func(**) # equals to my_func(p1=a, p2=b) 

The second thing you need is to get the variable by it’s name. Python has a possibility to do this, but it depends on where the variable is stored.

If it’s an object attribute:

my_obj.var # can be getattr(my_obj, 'var') 

locals gives you all local variables as dict . There is also a similar globals function.

So far the examples above are useless, but the idea is that you use python object (list, dict or str) instead of writing down the variable name itself.

So you can combine it all to build a tuple

def my_func(): var1, var2, var3, var4 = range(10, 14) vars = ['var1', 'var2', 'var3'] loc = locals() # var1 - var4 and vars are available as dict now tpl = tuple(loc[k] for k in vars) print(tpl) print(tuple([var1, var2, var3])) 

So with this you can replace

x = np.concatenate((var1, var2, var3), axis = 1) # to x = np.concatenate(tpl, axis=1) 

This code will be fragile — moving part of it to another func may break it. And I think that this code style is not easy to read. So in most cases I’d suggest you to search for another approach. Combining all variables in some structure (dict or object) as suggested in first comment may be much better. But I can’t say it will work as I don’t see the whole your code.

Источник

How do I pass variables across functions? [duplicate]

I want to pass values (as variables) between different functions. For example, I assign values to a list in one function, then I want to use that list in another function:

list = [] def defineAList(): list = ['1','2','3'] print "For checking purposes: in defineAList, list is",list return list def useTheList(list): print "For checking purposes: in useTheList, list is",list def main(): defineAList() useTheList(list) main() 
  1. Initialize ‘list’ as an empty list; call main (this, at least, I know I’ve got right. )
  2. Within defineAList(), assign certain values into the list; then pass the new list back into main()
  3. Within main(), call useTheList(list)
  4. Since ‘list’ is included in the parameters of the useTheList function, I would expect that useTheList would now use the list as defined by defineAList(), NOT the empty list defined before calling main.
For checking purposes: in defineAList, list is ['1', '2', '3'] For checking purposes: in useTheList, list is [] 

«return» does not do what I expected. What does it actually do? How do I take the list from defineAList() and use it within useTheList()?

I don’t want to use global variables.

8 Answers 8

This is what is actually happening:

global_list = [] def defineAList(): local_list = ['1','2','3'] print "For checking purposes: in defineAList, list is", local_list return local_list def useTheList(passed_list): print "For checking purposes: in useTheList, list is", passed_list def main(): # returned list is ignored returned_list = defineAList() # passed_list inside useTheList is set to global_list useTheList(global_list) main() 
def defineAList(): local_list = ['1','2','3'] print "For checking purposes: in defineAList, list is", local_list return local_list def useTheList(passed_list): print "For checking purposes: in useTheList, list is", passed_list def main(): # returned list is ignored returned_list = defineAList() # passed_list inside useTheList is set to what is returned from defineAList useTheList(returned_list) main() 

You can even skip the temporary returned_list and pass the returned value directly to useTheList :

def main(): # passed_list inside useTheList is set to what is returned from defineAList useTheList(defineAList()) 

You’re just missing one critical step. You have to explicitly pass the return value in to the second function.

def main(): l = defineAList() useTheList(l) 
def main(): useTheList(defineAList()) 

Or (though you shouldn’t do this! It might seem nice at first, but globals just cause you grief in the long run.):

l = [] def defineAList(): global l l.extend(['1','2','3']) def main(): global l defineAList() useTheList(l) 

The function returns a value, but it doesn’t create the symbol in any sort of global namespace as your code assumes. You have to actually capture the return value in the calling scope and then use it for subsequent operations.

Thank you- I appreciate that you provided not only an example, but an explanation of why it works that way.

return returns a value. It doesn’t matter what name you gave to that value. Returning it just «passes it out» so that something else can use it. If you want to use it, you have to grab it from outside:

lst = defineAList() useTheList(lst) 

Returning list from inside defineAList doesn’t mean «make it so the whole rest of the program can use that variable». It means «pass the value of this variable out and give the rest of the program one chance to grab it and use it». You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = [] . Inside defineAList , you create a new list and return it; this list has no relationship to the one you defined with list = [] at the beginning.

Incidentally, I changed your variable name from list to lst . It’s not a good idea to use list as a variable name because that is already the name of a built-in Python type. If you make your own variable called list , you won’t be able to access the builtin one anymore.

Источник

Python Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

Example

def my_function(food):
for x in food:
print(x)

fruits = [«apple», «banana», «cherry»]

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью