Search code examples
pythonlistif-statementcase-statement

A simpler list of cases


I have to test many cases, but this solution is not very elegant:

if '22' in name:
    x = 'this'
elif '35' in name:
    x = 'that'
elif '2' in name:    # this case should be tested *after* the first one
    x = 'another'
elif '5' in name:
    x = 'one'
# and many other cases

Is there a way to do this sequence of cases with a list?

L = [['22', 'this'], ['35', 'that'], ['2', 'another'], ['5', 'one']]

Solution

  • Use next to take the first value from a generator.

    x = next((val for (num, val) in L if num in name), 'default value')
    

    The first argument of next is the generator to consume, and the second is the default value if the generator is entirely consumed without producing a value.