How to iterate through two list in python

Question:

I have 2 list, which i would like to iterate through and capture the selection/input from user.

list1 = ['E1', 'E2', 'E3']
list2 = ['api1', 'api2', 'api3', 'api4']

def display_option(options):
    for env_option, type in enumerate(options,1):
        print("t{}. {}".format(env_option, type))

def select_option_from_list_of_values(item):
    while True:
        print("this option available for selection:")
        display_option(item)
        print("n")
        option = input("Please enter the option: ")
        print("n")

not sure how to iterate through, i want to display result something like below :

this option available for selection:

    1. E1
    2. E2
    3. E3

Please enter the option: 2

this option available for selection

    1. api1
    2. api2
    3. api3
    4. api4

Please enter the option: 3

NOTE: I am new to python. Appreciate all the help.

I tried writing a basic loop function to iterate through list’s but unsuccessful.

Asked By: bprat3

||

Answers:

You have the code, you just didn’t validate and return the value you fetched.

list1 = ['E1', 'E2', 'E3']
list2 = ['api1', 'api2', 'api3', 'api4']

def display_option(options):
    for env_option, text in enumerate(options,1):
        print("t{}. {}".format(env_option, text))

def select_option_from_list_of_values(item):
    while True:
        print("this option available for selection:")
        display_option(item)
        print("n")
        option = input("Please enter the option: ")
        option = int(option)
        if option-1 < len(item):
            return option
        print("Out of range")

i = select_option_from_list_of_values(list1)
j = select_option_from_list_of_values(list2)
print(i,j)

Error checking is an exercise left to reader. (Like, what if they don’t enter an integer?

Answered By: Tim Roberts

When taking numeric user input you should always check that the value entered can be interpreted as a number. In this case you also need to validate that the number is within the range of the list size.

list1 = ['E1', 'E2', 'E3']
list2 = ['api1', 'api2', 'api3', 'api4']

def display_options(_list):
    print('These option are available for selection...')
    for i, o in enumerate(_list, 1):
        print(f't{i}. {o}')

def choose_option(_list):
    while True:
        display_options(_list)
        try:
            choice = int(input('Select option nunber: '))
            if choice < 1 or choice > len(_list):
                raise ValueError('Invalid option')
            print(f'You chose {_list[choice-1]}')
            break
        except ValueError as e:
            print(e, 'a')

for _list in list1, list2:
    choose_option(_list)
Answered By: Pingu