Skip to content

Python users choose from the list | Example code

  • by

Use for loop with enumerate function and take input as an integer value. Using this logic will allow to users choose from the list in Python.

Example users choose from the list in Python

Simple example code gives the user to choose an option on the command line.

def let_user_pick(options):
    print("Please choose:")

    for idx, element in enumerate(options):
        print("{}) {}".format(idx + 1, element))

    i = input("Enter number: ")
    try:
        if 0 < int(i) <= len(options):
            return int(i) - 1
    except:
        pass
    return None


options = ["Option 1", "Option 2", "Option 3"]
res = let_user_pick(options)

print(options[res])

Output:

Python users choose from the list

Or you can use the inquirer module.

You can install inquirer with pip :

pip install inquirer

Multiple choices

One of the inquirer’s features is to let users select from a list with the keyboard arrows keys, not requiring them to write their answers. This way you can achieve better UX for your console application.

Here is an example is taken from the documentation :

import inquirer
questions = [
  inquirer.List('size',
                message="What size do you need?",
                choices=['Jumbo', 'Large', 'Standard', 'Medium', 'Small', 'Micro'],
            ),
]
answers = inquirer.prompt(questions)
print answers["size"]

Note: As far as I know, it won’t work on Windows without some trick.

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this Python List topic.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.