Can the match-case statement in Python handle complex data structures?

Can the match-case statement in Python handle complex data structures?

a) Yes, it can match patterns in lists, dictionaries, and tuples
b) No, it only works with simple data types
c) Yes, but only with strings
d) No, it only works with numbers

Answer:

a) Yes, it can match patterns in lists, dictionaries, and tuples

Explanation:

The match-case statement in Python is capable of matching patterns in complex data structures such as lists, dictionaries, and tuples. This allows you to deconstruct and examine the contents of these structures in a concise and readable manner.

def process_data(data):
    match data:
        case [x, y]:
            return f"List with two elements: {x}, {y}"
        case {"key": value}:
            return f"Dictionary with key-value pair: {value}"
        case _:
            return "Unknown data structure"

In this example, the match-case statement is used to handle different data structures, demonstrating its versatility in pattern matching. This capability is particularly useful when processing or validating complex data formats.

The ability to handle complex data structures with match-case significantly enhances the expressiveness and power of Python, making it easier to work with diverse data in a clean and efficient way.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top