In this lesson, you’ll see that functions in Python are first class objects, which means you can pass them to other functions as arguments, return them from other functions as values, and store them in variables and data structures. You’ll see how to assign a function to a list data structure. This flexible feature in Python will allow you to emulate switch case.
Functions Are First-Class Citizens in Python
00:00 The way to do that is by leveraging the fact that Python has first-class functions. So, functions in Python—they’re just like any other object. You can pass them as arguments to other functions, and you can return them from functions as values, and you can store them in variables and store them in data structures.
So, this is actually a really flexible feature in Python. To give you an example, we can define a simple function here that takes two arguments and just returns the sum of both. I could actually go ahead and say, “Hey, I’m going to store this function in a list that I’m going to call my
funcs,” and then I could just refer—whoops—I could just refer to that function and call it. Right?
So if I did that, I would actually get a result that is
5 because it’s adding together
3, right? I would just, with the index here, grab the first function in there—which is
myfunc(), which we defined up there—and then I can just call it with the braces syntax. So,
Become a Member to join the conversation.