Storing Functions in a List - Python Q&A

Click For Summary
SUMMARY

Storing multiple functions in a list is a straightforward task in Python. Users can define functions such as func1, func2, and func3, and then store them in a list, allowing for easy iteration and execution. The example provided demonstrates how to create a list A containing these functions and call each function in a loop, resulting in the output of their respective print statements.

PREREQUISITES
  • Understanding of Python function definitions
  • Familiarity with Python lists
  • Basic knowledge of Python iteration using loops
  • Experience with Python print statements
NEXT STEPS
  • Explore Python higher-order functions and their applications
  • Learn about Python decorators and their usage
  • Investigate the concept of function closures in Python
  • Study the differences between lists and tuples in Python
USEFUL FOR

Python developers, students learning programming concepts, and anyone interested in functional programming techniques in Python.

zeion
Messages
455
Reaction score
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
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
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
Replies
6
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 18 ·
Replies
18
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 34 ·
2
Replies
34
Views
6K