Skip to content
Home » Jump Tables in Python

Jump Tables in Python

Spread the love

Today we’ll be talking about jump tables. These are structures containing functions, usually lists or dictionaries. We can choose the function we need using its index or key.

jump tables

Jump tables can contain both named and anonymous functions. The former are created by means of the def statement. The latter are created by means of lambda expressions.

If you want to learn more about lambda expressions, I have an article about them, so feel free to read it.

OK, let’s see a jump table in action. First let’s create some simple functions and store them in a list, along with some lambda functions:

def sing(title, author):
    return f"singing '{title}' by {author}"

def read(title, author):
    return f"reading '{title}' by {author}"

def act(title, author):
    return f"acting in '{title}' by {author}"

functions = [sing, 
             read, 
             act, 
             lambda title, author: f"doing stuff with '{title}' by {author}"]

print(functions[0]("Unexpected Visitors", "Rose Parker"))
print(functions[1]("Unexpected Visitors", "Rose Parker"))
print(functions[2]("Unexpected Visitors", "Rose Parker"))
print(functions[3]("Unexpected Visitors", "Rose Parker"))

The output is:

singing 'Unexpected Visitors' by Rose Parker
reading 'Unexpected Visitors' by Rose Parker
acting in 'Unexpected Visitors' by Rose Parker
doing stuff with 'Unexpected Visitors' by Rose Parker

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

We can choose any function from the list. We could also iterate over the functions in a for loop.

Now let’s have an example with a dictionary:

def sing():
    return "la la la"

def bark():
    return "woof woof"

def speak():
    return "blah, blah, blah"

functions = {"morning": sing, 
             "afternoon": bark, 
             "evening": speak, 
             "night": lambda: "zzz"}

time = input("What time of the day is it now?: ")
print(f"This is what I can hear behind the wall: {functions[time]()}")

The output:

What time of the day is it now?: night
This is what I can hear behind the wall: zzz

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply