Using the
input()
function in Python, we can accept the input from the user. The
input()
the function takes the user-entered data as a string data type, and if we want that data into a different format, we have to convert it using some Python functions and methods. In this tutorial, we will discuss how to input a list in Python. By the end of this tutorial, you will have a solid understanding of how can we can convert user input data to a list in Python.
How to get a list of numbers as input from a user?
Here are the steps to make a list as input in Python.
Step1: Write the input function
The first step, write the
input()
function and pass the appropriate input message argument that will be printed when Python executes the input() function.
num_list = input("Enter a list of numbers seperated with space: ")
Step 2: apply the split() method to the input function
The
split()
is a string method that, by default, breaks a string into a list of words by spaces. We can use this string method to convert a delimiter-separated string value to a list.
num_list = input("Enter a list of numbers seperated with space: ").split()
Step 3: iterate over the list elements and convert the data type
The split() method will convert the string into a list, but its elements will remain in the string data type. To convert it into an integer or number, we have to iterate over every element of the list and convert it into an int using the int() function.
for i in range(num_list): #convert the data type of every item of the list to int num_list = (num_list[i])
Instead of using the for loop, we could also have used the map function to convert the data type of the list elements. example
num_list = list(map(int, num_list))
Example 1:
Accept a list of numbers as input from the user and compute the average.
#ask the user to enter the items num_list = input("Enter the list of numbers separated by space: ") #convert the user entered string to list num_list = num_list.split() #convert every item of the list to integer for i in range(len(num_list)): num_list[i] = int(num_list[i]) #compute the average of num_list average = sum(num_list)/len(num_list) print(f"The average of {num_list} is: {round(average,2)}")
Output
Enter the list of numbers separated by space: 98 97 99 95 96 94 The average of [98, 97, 99, 95, 96, 94] is: 96.5
Example 2:
Accept the list of numbers from the user and compute its sum. In the above example, we have used the for loop to convert every item of the
num_list
to an integer. In this example, we will replace that for loop statement and try to perform the same tasks using the Python
map()
function.
#ask the user to enter the items num_list = input("Enter the list of numbers separated by space: ") #convert the user entered string to list num_list = num_list.split() #convert every item of the list to integer num_list = list(map(int, num_list)) #sum of the list total = sum(num_list) print(f"The sum of {num_list} is: {total}")
Output
Enter the list of numbers separated by space: 100 200 300 400 500 The sum of [100, 200, 300, 400, 500] is: 1500
Example 3:
Accept the list of comma-separated numbers from the user and compute its sum. By default, the
split()
method converts a string into a list of items that are separated by space. It also accepts an optional argument separator that defines on which basis the method must split the string. We can pass the
','
argument to the
split()
method, and it will
split()
the string separated by
,
.
#ask the user to enter the items num_list = input("Enter the list of numbers separated by comma (,) : ") #convert the user entered string to list num_list = num_list.split(',') # "1,2,3,4,5,6" to ["1", "2", "3", "4", "5", "6"] #convert every item of the list to integer num_list = list(map(int, num_list)) #sum of the list total = sum(num_list) print(f"The sum of {num_list} is: {total}")
Output
Enter the list of numbers separated by comma (,) : 100,200,300,400,500,600 The sum of [100, 200, 300, 400, 500, 600] is: 2100
Input a list of numbers using the input() and for loop
In the above section, we see how to use the split() method to convert the user-entered value to a list. Now let's see how we can use the input() function with the for loop and input a list of numbers from the user. Steps to Input a list of numbers using the input() and for loop
Step 1:
Create an empty list
num_list = []
Step 2:
Ask the user to enter the size of the list and accept it as an integer.
size = int(input("Size of the list?: "))
Step 3:
Run a loop from range 0 to
size
using the
for
loop and
range()
function
for i in range(size):
Step 4:
Inside the for loop, uses the
input()
function to accept the list item as an integer.
num = int(input("Enter the number: "))
Step 5:
After accepting the number, append it to the empty list
num_list
using the
append()
method.
num_list.append(num)
Example:
Accept a list of integer numbers as input from the user and compute the average of the list.
#declare an empty list num_list = [] #size of the list size = int(input("Enter the size of the list: ")) for i in range(size): #ask user to enter the list items num = int(input("Enter Number: ")) #add the user entered number to the list num_list.append(num) #average of the list average = sum(num_list)/size print(f"The Average of list {num_list} is: ", round(average,2))
Output
Enter the size of the list: 5 Enter Number: 98 Enter Number: 90 Enter Number: 97 Enter Number: 96 Enter Number: 95 The Average of list [98, 90, 97, 96, 95] is: 95.2
Input a list of numbers using list comprehension
In the above example, we used the
for
loop to execute the
input()
and
append()
functions multiple times to add data into an empty python list. With the help of list comprehension, we can short-hand some of the multiple-line code and write the above same
for
loop statement and its body using a single line of code.
syntax
this is the syntax to input a list of numbers using list comprehension
list_name = [int(input()) for i in range(size)]
Example
Write a script in Python that accepts a list of numbers from the user using list comprehension.
#size of the list size = int(input("Enter the size of the list: ")) num_list = [int(input("Enter Number: ")) for i in range(size)] #average of the list average = sum(num_list)/size print(f"The Average of list {num_list} is: ", round(average,2))
Output
Enter the size of the list: 5 Enter Number: 98 Enter Number: 97 Enter Number: 96 Enter Number: 97 Enter Number: 98 The Average of list [98, 97, 96, 97, 98] is: 97.2
How to accept nested list input in Python
A Python nested list is also known as a multi-dimensional list. During programming, we may encounter cases where we need to ask the user to enter the value for a matrix(A matrix is a two-dimensional array or list). In such cases, we can write a script that accepts nested lust as an input.
Example
Write a program to input a nested list in Python
#rows and columns of the matrix rows = 4 #input nested list using list comprehension nested_list = [list(map(int, input("Enter row data: ").split())) for i in range(rows)] print("The nested list is: ", nested_list)
Output
Enter row data: 1 2 3 4 Enter row data: 5 6 7 8 Enter row data: 9 10 11 12 Enter row data: 13 14 15 16 The nested list is: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
Conclusion
In Python, to input value from the user, we use Python's
input()
function. The
input()
function accepts the user input as a string data type, and to convert it into a list or any other data type, we have to use the
split()
method or any other type conversion function. In this tutorial, we learned the different techniques to convert the user input to a list of numbers.
To convert a user input value to a list, we used the
split()
method on the user input data. The
split()
method breaks the string value into a list of string number values separated by the space. And to convert those string number values to
int
we can use different approaches, among which the
map()
function is most efficient and legible.
People are also reading:
- Find K-th Smallest Element in BST
- Check if directed graph is connected
- Modular Exponentiation in Logarithmic Time
- Delete Nodes And Return Forest
- Longest Consecutive Sequence in Linear time
- Print a given matrix in spiral form
- How to remove an element from a list in Python
- Program to Rotate an Array
- Merge Two Sorted Arrays in-place
- Print all subarrays with 0 sum
- Find Maximum Subarray Sum
Leave a Comment on this Post