How to iterate through two list in python

Advertisements

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.

>Solution :

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?

Leave a ReplyCancel reply