Storing Functions in a List - Python Q&A

In summary, to store a function in a list in Python, you can use the list's append() method. This allows you to add multiple functions to a single list. To call a function stored in a list, you can use the list's index notation. It is also possible to pass arguments to a function stored in a list and modify the function using the list's index notation.
  • #1
zeion
466
1

Homework Statement



Hello,

I just have a small question with Python.

Is it possible to store multiple functions in a list? So I can call them from the list?

Like if I had :

def func1():
...

def func2():
...

def func3():
...

Can I put them in a list and call them from the list?

Thanks.

Homework Equations





The Attempt at a Solution

 
Technology news on Phys.org
  • #2
Hey zeion,

Try this:

Code:
>>> def func1():
...     print "1"
...
>>> def func2():
...     print "2"
...
>>> def func3():
...     print "3"
...
>>> A = [func1, func2, func3]
>>>
>>> for a in A:
...     a()
...
1
2
3

- Warren
 

1. How do you store a function in a list in Python?

To store a function in a list in Python, you simply need to use the list's append() method. For example, if you have a function named add, you can store it in a list named functions by using functions.append(add).

2. Can you store multiple functions in a single list in Python?

Yes, you can store multiple functions in a single list in Python. You can use the list's append() method to add functions to the list one by one, or you can create the list with all the functions already inside it.

3. How do you call a function stored in a list in Python?

To call a function stored in a list in Python, you can use the list's index notation. For example, if your function is stored at index 0 in the list functions, you can call it by using functions[0]().

4. Is it possible to pass arguments to a function stored in a list in Python?

Yes, it is possible to pass arguments to a function stored in a list in Python. When calling the function, you can pass the arguments in the same way as you would for a regular function, for example functions[0](arg1, arg2).

5. Can you modify a function stored in a list in Python?

Yes, you can modify a function stored in a list in Python. Since functions are mutable objects, you can use the list's index notation to access the function and modify it in any way you want.

Similar threads

  • Programming and Computer Science
Replies
3
Views
313
Replies
6
Views
644
  • Programming and Computer Science
Replies
1
Views
275
  • Programming and Computer Science
Replies
8
Views
793
  • Programming and Computer Science
Replies
2
Views
766
  • Programming and Computer Science
Replies
34
Views
2K
  • Programming and Computer Science
Replies
9
Views
2K
  • Programming and Computer Science
Replies
8
Views
953
  • Programming and Computer Science
Replies
15
Views
1K
  • Programming and Computer Science
Replies
5
Views
2K
Back
Top