How to find the tuples that start with a specific prefix in a list of tuples with Python

2 Answers

0 votes
def prefix_tuple(lst_tpl, prefix):
    result = []

    for tpl in lst_tpl:
        string = tpl[0]
        if string.startswith(prefix):
            result.append(tpl)
    
    return result


lst_tpl = [('Puzzle', 84),('Internet', 10), ('Python', 64), ('Games', 99), ('Pyramid', 37)]
prefix = 'Py'

print(prefix_tuple(lst_tpl, prefix))


  
'''
run:

[('Python', 64), ('Pyramid', 37)]
  
'''

 



answered Feb 10 by avibootz
edited Feb 10 by avibootz
0 votes
def prefix_tuple(lst_tpl, prefix):
    return [t for t in lst_tpl if t[0].startswith(prefix)]


lst_tpl = [('Puzzle', 84), ('Internet', 10), ('Python', 64), ('Games', 99), ('Pyramid', 37)]
prefix = 'Py'

print(prefix_tuple(lst_tpl, prefix))


  
'''
run:

[('Python', 64), ('Pyramid', 37)]
  
'''

 



answered Feb 10 by avibootz
...