How to get a list of numbers as input in Python

Hey everyone, in this post we will learn how to get a list of numbers as input in Python. Suppose the user wants to give some numbers as input and wishes it to be stored in a list, then what Python code you will need to add in your program to accomplish this. Let’s discuss it step by step.

Getting a list of numbers as input in Python

As we all know, to take input from the user in Python we use input() function. So let’s use it in our below example code.

inp = input()

Output:

1 3 5 7

So here, we enter “1 3 5 7” as input and store the input in a variable called input. Now we need to split the input to get access to the individual numbers. Let’s do it.

numbers = inp.split()

print(numbers)

Output:

[‘1’, ‘3’, ‘5’, ‘7’]

As you can see in the output, now we have a list of strings stored in the variable numbers. Note that the input() function in Python always returns a string.

But we want a list of numbers(say integers) as input. So what do we do?

Well, we need to typecast the elements stored in the variable numbers to integers and then store them in a list. See the below code.

list_of_numbers = []

for n in numbers:
    list_of_numbers.append(int(n))

print(list_of_numbers)

Output:

[1, 3, 5, 7]

We can do the above also by using the map() function. Using the map()  function shortens our code. Read more about the map() function here: Python map() function

Have a look at the given Python code.

list_of_numbers = list(map(int, numbers))

print(list_of_numbers)

Output:

[1, 3, 5, 7]

Okay, so that’s done. We have written the code for getting a list of numbers as input. There is just one more thing to do- doing it all in a single line of code. And here we go.

list_of_numbers = list(map(int, input().split()))

print(list_of_numbers)

Output:

1 3 5 7
[1, 3, 5, 7]

Another way to get some numbers as input and store it in a list is as follows. This method uses the list comprehension technique.

list_of_numbers = [int(i) for i in input().split()]

print(list_of_numbers)

Output:

1 3 5 7
[1, 3, 5, 7]

Thank you.

Also read:

String split and join in Python
List and dictionary comprehension in python
How to take multiple inputs in a single line: Python?

Leave a Reply

Your email address will not be published. Required fields are marked *