How to get value of a list by enumerate numbers

i want to get values from a list by choosing enumerate numbers (1, 2 or 3) on the display, so the choosen variable will results a value from the list not the characters that i type from the input

List = ['apple', 'berry', 'cherry']

List_Display = '\n'.join(['[{}]{}'.format(n,i) for n, i in (enumerate(List,start=1))])

print(List_Display)

choosen = []

choose = input('Enter choices: ')

if choose in List_Display:

    choosen.append(choose)

    print('choosen:',choosen)

else:

    print('No item choosed') 

>Solution :

You will have to convert your input to an integer and adjust it with -1 because the index of a list starts with 0. Then you have to check if you have a valid index.

fruits = ['apple', 'berry', 'cherry']

fruits_display = '\n'.join([f'[{i}]{n}' for i, n in (enumerate(fruits, start=1))])
print(fruits_display)

selected = []
user_input = int(input('Enter choices: ')) - 1
if 0 <= user_input < len(fruits):
    selected.append(fruits[user_input])
    print('choosen:',selected)
else:
    print('No item choosed')

Leave a Reply