{"id":3163,"date":"2026-11-25T06:31:23","date_gmt":"2026-11-25T06:31:23","guid":{"rendered":"https:\/\/gyanipandit.com\/programming\/?p=3163"},"modified":"2026-11-25T06:31:42","modified_gmt":"2026-11-25T06:31:42","slug":"python-structural-pattern-matching","status":"publish","type":"post","link":"https:\/\/gyanipandit.com\/programming\/python-structural-pattern-matching\/","title":{"rendered":"Python Structural Pattern Matching (match-case) with Examples"},"content":{"rendered":"<p><strong>Structural pattern matching<\/strong>, added in <strong>Python 3.10<\/strong>, introduces the <code>match<\/code> and <code>case<\/code> statements. At first glance it looks like the <code>switch-case<\/code> of C, C++ or Java, but it is far more powerful. It can match exact values, several alternatives, lists of a certain shape, dictionaries with certain keys, and even objects, and it can pull values out of them at the same time.<\/p>\n<p><strong>Note:<\/strong> <code>match<\/code> needs Python 3.10 or newer. Check your version with <code>python --version<\/code>.<\/p>\n<h2>Syntax<\/h2>\n<pre class=\"wp-block-code\"><code>match subject:\n    case pattern1:\n        # runs if subject matches pattern1\n    case pattern2:\n        # runs if subject matches pattern2\n    case _:\n        # runs if nothing else matched (wildcard)<\/code><\/pre>\n<p>Python checks the cases from top to bottom and runs only the <strong>first<\/strong> one that matches. There is no &#8220;fall-through&#8221;, so you do not need <code>break<\/code>.<\/p>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" src=\"https:\/\/gyanipandit.com\/programming\/wp-content\/uploads\/2022\/10\/STRUCTURAL-PATTERN-MATCHING-IN-PYTHON.jpg\" alt=\"Python match case syntax\" \/><\/figure>\n<h2>1. Literal Patterns: a Simple Menu<\/h2>\n<pre class=\"wp-block-code\"><code>def drink(choice):\n    match choice:\n        case 1:\n            return \"You selected milk. Here is your milk!\"\n        case 2:\n            return \"You selected tea. Here is your tea!\"\n        case 3:\n            return \"You selected coffee. Here is your coffee!\"\n        case _:\n            return \"Sorry, only milk, tea and coffee are available.\"\n\nprint(drink(1))\nprint(drink(5))<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>You selected milk. Here is your milk!\nSorry, only milk, tea and coffee are available.<\/code><\/pre>\n<p>The underscore <code>_<\/code> is the <strong>wildcard<\/strong>. It matches anything, so it works like <code>default<\/code> in other languages.<\/p>\n<h2>2. OR Patterns with |<\/h2>\n<pre class=\"wp-block-code\"><code>def status(code):\n    match code:\n        case 200:\n            return \"OK\"\n        case 301 | 302:\n            return \"Redirect\"\n        case 400 | 401 | 403 | 404:\n            return \"Client error\"\n        case 500:\n            return \"Server error\"\n        case _:\n            return \"Unknown status\"\n\nfor c in (302, 404, 999):\n    print(c, status(c))<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>302 Redirect\n404 Client error\n999 Unknown status<\/code><\/pre>\n<h2>3. Guards: Adding an if Condition<\/h2>\n<p>A <strong>guard<\/strong> is an <code>if<\/code> written after the pattern. The case runs only if the pattern matches <em>and<\/em> the condition is true. Here an ATM accepts only multiples of 500:<\/p>\n<pre class=\"wp-block-code\"><code>def withdraw(amount):\n    match amount:\n        case int() if amount &gt; 0 and amount % 500 == 0:\n            return f\"Processing withdrawal of Rs {amount}\"\n        case int() if amount &gt; 0:\n            return \"Invalid amount. Only multiples of 500 are allowed.\"\n        case _:\n            return \"Please enter a positive whole number.\"\n\nfor a in (1000, 120, -500):\n    print(withdraw(a))<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>Processing withdrawal of Rs 1000\nInvalid amount. Only multiples of 500 are allowed.\nPlease enter a positive whole number.<\/code><\/pre>\n<p><code>int()<\/code> here is a class pattern: it matches any integer.<\/p>\n<h2>4. Sequence Patterns: Matching the Shape of a List<\/h2>\n<p>This is where <code>match<\/code> goes beyond a switch statement. It can check how many items a list has and capture them into variables:<\/p>\n<pre class=\"wp-block-code\"><code>def command(text):\n    match text.split():\n        case [\"quit\"]:\n            return \"Goodbye!\"\n        case [\"go\", direction]:\n            return f\"You walk {direction}.\"\n        case [\"pick\", \"up\", item]:\n            return f\"You picked up the {item}.\"\n        case [\"drop\", *items]:\n            return f\"You dropped: {', '.join(items)}\"\n        case _:\n            return \"I don't understand.\"\n\nfor t in (\"go north\", \"pick up sword\", \"drop key coin map\", \"quit\", \"dance\"):\n    print(command(t))<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>You walk north.\nYou picked up the sword.\nYou dropped: key, coin, map\nGoodbye!\nI don't understand.<\/code><\/pre>\n<p><code>direction<\/code> and <code>item<\/code> are <strong>capture patterns<\/strong>: they match any single value and store it. <code>*items<\/code> collects all remaining values into a list.<\/p>\n<h2>5. Mapping Patterns: Matching Dictionaries<\/h2>\n<p>Very useful for JSON data from an API:<\/p>\n<pre class=\"wp-block-code\"><code>def area(shape):\n    match shape:\n        case {\"type\": \"circle\", \"radius\": r}:\n            return round(3.14159 * r * r, 2)\n        case {\"type\": \"rectangle\", \"width\": w, \"height\": h}:\n            return w * h\n        case _:\n            return None\n\nprint(area({\"type\": \"circle\", \"radius\": 3}))\nprint(area({\"type\": \"rectangle\", \"width\": 4, \"height\": 5, \"color\": \"red\"}))\nprint(area({\"type\": \"triangle\"}))<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>28.27\n20\nNone<\/code><\/pre>\n<p>A mapping pattern only checks the keys you mention. Extra keys, like <code>\"color\"<\/code>, are ignored.<\/p>\n<h2>6. Class Patterns: Matching Objects<\/h2>\n<pre class=\"wp-block-code\"><code>from dataclasses import dataclass\n\n@dataclass\nclass Point:\n    x: int\n    y: int\n\ndef where(p):\n    match p:\n        case Point(x=0, y=0):\n            return \"Origin\"\n        case Point(x=0, y=y):\n            return f\"On the Y-axis at y={y}\"\n        case Point(x=x, y=0):\n            return f\"On the X-axis at x={x}\"\n        case Point(x=x, y=y):\n            return f\"Somewhere else: ({x}, {y})\"\n\nfor p in (Point(0, 0), Point(0, 5), Point(3, 0), Point(2, 7)):\n    print(where(p))<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>Origin\nOn the Y-axis at y=5\nOn the X-axis at x=3\nSomewhere else: (2, 7)<\/code><\/pre>\n<h2>The Most Common Mistake: Using a Variable Name as a Constant<\/h2>\n<pre class=\"wp-block-code\"><code>RED = \"red\"\n\nmatch colour:\n    case RED:          # does NOT compare with \"red\"!\n        ...\n    case \"blue\":\n        ...<\/code><\/pre>\n<p>A bare name in a case is a capture pattern. It matches <em>everything<\/em> and stores the value in <code>RED<\/code>. Python spots this and refuses to run the code:<\/p>\n<pre class=\"wp-block-code\"><code>SyntaxError: name capture 'RED' makes remaining patterns unreachable<\/code><\/pre>\n<p>Use a literal (<code>case \"red\":<\/code>) or a dotted name such as an Enum member (<code>case Colour.RED:<\/code>) instead.<\/p>\n<h2>match-case vs if-elif<\/h2>\n<ul>\n<li>For two or three simple comparisons, <code>if-elif<\/code> is perfectly fine.<\/li>\n<li>Use <code>match<\/code> when you are checking the <em>structure<\/em> of data (lists, dictionaries, objects) or have many alternatives. It is shorter and easier to read.<\/li>\n<\/ul>\n<h2>Frequently Asked Questions<\/h2>\n<h3>Does Python have a switch statement?<\/h3>\n<p>Not by that name, but since Python 3.10, <code>match-case<\/code> does everything a switch does and much more.<\/p>\n<h3>What does case _ mean?<\/h3>\n<p>It is the wildcard pattern. It matches anything and is used as the default case.<\/p>\n<h3>Do I need break in match-case?<\/h3>\n<p>No. Only the first matching case runs; there is no fall-through.<\/p>\n<p>Related: <a href=\"https:\/\/gyanipandit.com\/programming\/python-list-sort\/\">Python list sort()<\/a> \u00b7 <a href=\"https:\/\/gyanipandit.com\/programming\/python-syntax\/\">Basic Python syntax<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Structural pattern matching, added in Python 3.10, introduces the match and case statements. At first glance it looks like the switch-case of C, C++ or Java, but it is far more powerful. It can match exact values, several alternatives, lists of a certain shape, dictionaries with certain keys, and even objects, and it can pull &#8230; <a title=\"Python Structural Pattern Matching (match-case) with Examples\" class=\"read-more\" href=\"https:\/\/gyanipandit.com\/programming\/python-structural-pattern-matching\/\" aria-label=\"Read more about Python Structural Pattern Matching (match-case) with Examples\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[25],"tags":[26,27],"class_list":["post-3163","post","type-post","status-publish","format-standard","hentry","category-python-tutorial","tag-python","tag-python-tutorial"],"_links":{"self":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts\/3163","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/comments?post=3163"}],"version-history":[{"count":3,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts\/3163\/revisions"}],"predecessor-version":[{"id":6158,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts\/3163\/revisions\/6158"}],"wp:attachment":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/media?parent=3163"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/categories?post=3163"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/tags?post=3163"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}