Read a List from Command Line

To read a list from command line in Python, we can use input(), and type-conversion functions as required.

The reading of list depend mostly on the format in which the user is instructed to enter.

For example, the user may enter the number of elements in the list, and then enter the elements one by one.

3
apple
banana
cherry

Or, the user may enter the list as some comma separated values, or space separated values.

apple banana cherry

In this tutorial, we will learn how to read a list of elements from user via command prompt or console, and store it in a variable. We shall cover the above two cases.

Read List Length and then Element by Element

In the following example, we read the length of list and then use For Loop to iteratively read the elements from console. We shall start with an empty list, and then append each element to the list.

Python Program

</>
Copy
try:
    n = int(input())
    myList = []
    for i in range(n):
        element = input()
        myList.append(element)
    print('List :', myList)
except ValueError:
    print('You entered an invalid input')

Output

3
apple
banana
cherry
List : ['apple', 'banana', 'cherry']

Read List of Integers

If the elements are integers, then, while reading the elements we have to explicitly convert the string returned by input() function to integer using int() function.

Python Program

</>
Copy
try:
    n = int(input())
    myList = []
    for i in range(n):
        element = int(input())
        myList.append(element)
    print('List :', myList)
except ValueError:
    print('You entered an invalid input')

Output

3
125
668
987
List : [125, 668, 987]

Read Space Separated Integers to a List

In this example, user enters a list of numbers with space as delimiter. We shall read the entire input as a string, then use string split operation to split the given string into list elements.

Python Program

</>
Copy
try:
    x = input()
    myList = x.split(' ')
    print('List :', myList)
except ValueError:
    print('You entered an invalid input')

Output

List : ['apple', 'banana', 'cherry']

Conclusion

In this Python Tutorial, we learned how to read a list of elements from user in some of the most used ways.