We Offer 100% Job Guarantee Courses (Any Degree / Diploma Candidates / Year GAP / Non-IT / Any Passed Outs). Placement Records
Hire Talent (HR):+91-9707 240 250

General

How to Input a List in Python?

How to Input a List in Python?

Introduction

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.

How to accept a number list as an input?

In python, we user can give a number list as an input.

Example:

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)

Output:

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.

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.

Example:

input_st= input (“schools names“)
school= input_st.split(",")
print("School names")
for name in school:
print(name)

Output:

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.

Related Blogs:

  1. Brief Overview of Python Language
  2. Python Career opportunities
  3. Python Break Continue
  4. Python Control Flow
  5. Python Data Types
  6. Python Dictionary
  7. Python Exception Handling
  8.  Python File
  9. Python Functions
  10. Python Substring
Besant Technologies WhatsApp