1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How to distinguish between a tuple and a list in Python's structural pattern matching?

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I want to use Python's structural pattern matching to distinguish between a tuple (e.g. representing a point) and a list of tuples.

    The straightforward approach does not work though:

    def fn(p):
    match p:
    case (x, y):
    print(f"single point: ({x}, {y})")
    case [*points]:
    print("list of points:")
    for x, y in points:
    print(f"({x}, {y})")

    fn((1, 1))
    fn([(1, 1), (2, 2)])


    which outputs:

    single point: (1, 1)
    single point: ((1, 1), (2, 2))


    whereas I want it to output:

    single point: (1, 1)
    list of points:
    (1, 1)
    (2, 2)


    Switching the order of the case statements also does not help here.

    What is a good way to solve this with pattern matching?

    Continue reading...

Compartilhe esta Página