How to Input a List in Python?
If you are using python, then sometimes you need to take a list as an input. In this article, we have a look on how to input a list in python.
Apart from this, we will also have a look at:
- How to accept a number list as an input?
- How to accept a string list from the user?
So, now, let’s get into it.
How to Input a list in python?
The list is one of the data structure in python. It is basically a collection of certain items. These items are separated by the comma (,) and the list is enclosed with the square brackets().
In python, to accept the inputs from the user, you can use input() function. Using this function, you can accept a string, integer or even a single character. However, each type of input requires a different approach.
Let’s have a look at each type of input.
Learn Python from the Basic to Advanced Level with Hands-on Training, Placements, and more with
Python Training in Bangalore
How to accept a number list as an input?
In python, we user can give a number list as an input.
input_string = input("Enter the number list: ") usList = input_string.split() print("Sum of the list ", usList) sum = 0 for num in userList: sum += int(num) print("Sum = ", sum)
Enter the number list: 2 4 6 9 Sum of the list Sum= 21
Now, let us understand how this program works:
- By using the input() function, it converts the input to a string and separates it with the spaces.
- You can also accept the string using the (,).
- Next, you can use the spilt() function for passing the argument.
- After this, using the input_string.split() you can separate the input string with space. Also, convert them into an individual element and add it to a list.
- Lastly, the ‘for’ loop is for converting every element into an integer for calculating its sum.
Next is, let us have a look at accepting the string list as an input.
Get Placement Oriented Python Training from Industry Experts with our Python Training in Chennai
How to accept a string list as an input?
Apart from the number list, we can also accept the string as an input from the user. In python, it is possible to get a string as an input.
input_st= input (“schools names“) school= input_st.split(",") print("School names") for name in school: print(name)
write the name of your schools Nkvv, Besant, stella School names Nkvv Besant Stella
Let me explain the program first:
- The input list elements of a string can be separated by a comma.
- With the input_st.split (“,”) we can split a string with the comma and create a list of string.
- Iterate a list with a for loop and print the school name.
Learn Python Course to Boost your Carrer with our Python Online Training