Putting the Structural in Structural Pattern Matching

The Turing Taco Tales
7 min readNov 19, 2023

Explore the power of structural pattern matching in Python. Learn to replace cumbersome if-elif-else chains for more clarity and efficiency. Stay tuned for our next article on matching tuples, lists, and dictionaries. Subscribe for more insights into advanced Python programming!

© 2023 The Turing Taco Tales / Oscar Mauricio Forero Carrillo

Originally published at The Turing Taco Tales on November 19, 2023.

A Python on top of a three-dimensional puzzle

Overview

After the first look at structural pattern matching, we’ll examine why the structural is part of the name.

We often use switch statements when writing code in languages like Java or C. These statements help us choose what to do based on a variable's value. They're great for making decisions without writing many 'if-else' statements. But they have a limit. They can't handle complex data like lists that require us to write extra code.

Another challenge is the ‘fallthrough’ behavior in C and Java. Without a break statement, a switch in C will continue executing the subsequent cases, which can be confusing. This is a poor choice for mapping multiple matches to the same action.

Java improved upon C by introducing the ability to use Strings in switch statements, a feature that added more…

--

--

No responses yet