Case clauses should be able to match list indexes

Python’s match-case statements can allow list indexes, variables, and constants to be matched to constants and variables — but not list indexes. Additionally, JavaScript already has this dynamic sort of feature in its switch-case statements. Do note, JavaScript actually uses value matching instead of structural pattern matching.

Issue 128313 created regarding this.

GH issue for reference:

This SO question may be a good starting point for prior discussion:

3 Likes

If additional syntax options for value patterns were to be added, it would be preferable if they genuinely allowed matching arbitrary values, rather than merely adding a further syntactic construct (item lookup) that is implicitly considered to be a value pattern.

While the overall explicit pattern matching syntax proposal in PEP 642 – Explicit Pattern Syntax for Structural Pattern Matching | peps.python.org was rejected in favour of the implemented pattern matching proposal, one of its subfeatures is syntactically compatible with the current pattern matching feature, and covers exactly this part of the value matching problem space: value constraints.

The idea behind value constraints is to allow == (and is) to be used as prefix operators in pattern matching clauses.

While they would be allowed to appear anywhere implicit value patterns (that is, name.attr) can appear in a case pattern, they read best when used as the sole clause in a case block:

lst = ['a', 'b', 'c'] # of options in this example

user_input = input(f'Input {lst[0]}, {lst[1]}, or {lst[2]}. \n: ').strip().lower()

match user_input:
    case == lst[0]:
        print('\nFirst option chosen. ')
        ...
    case == lst[1]:
        print('\nSecond option chosen. ')
        ...
    case == lst[2]:
        print('\nThird option chosen. ')
        ...
    case _:
        print('\nInvalid input. Kindly try again.')
        ...

This has an obvious (and accurate) mapping to the corresponding if-elif chain:

if user_input == lst[0]:
    print('\nFirst option chosen. ')
    ...
elif user_input == lst[1]:
    print('\nSecond option chosen. ')
    ...
elif user_input == lst[2]:
    print('\nThird option chosen. ')
    ...
else:
    print('\nInvalid input. Kindly try again.')
    ...
3 Likes

Thank you for commenting and for your feedback :blush:

I also edited the issue to reflect this, though I’m not too sure if I captured everything covered there. If you notice any problems in the original issue — such as use of potentially incorrect or ambiguous terminology — please do let me know so I can address them.

Honestly, I did not think my proposal would be entertained thus far anyway, so I’m glad to have your support.

Again, thank you so much!