4

How do I take a specific number of input in python. Say, if I only want to insert 5 elements in a list then how can I do that? I tried to do it but couldn't figure out how.

In the first line I want to take an integer which will be the size of the list. Second line will consist 5 elements separated by a space like this:

5

1 2 3 4 5

Thanks in advance.

Varun Sharma
  • 57
  • 1
  • 6

2 Answers2

1
count = int(raw_input("Number of elements:"))
data = raw_input("Data: ")
result = data.split(sep=" ", maxsplit=count)
if len(result) < count:
    print("Too few elements")

You can also wrap int(input("Number of elements:")) in try/except to ensure that first input is actually int.

p.s. here is helpful q/a how to loop until correct input.

Sergey Belash
  • 1,433
  • 3
  • 16
  • 21
1

Input :-

5

1 2 3 4 5

then, use the below code :


n = int(input())    # Number of elements

List = list ( map ( int, input().split(" ") ) )

Takes the space separated input as list of integers. Number of elements count is not necessary here. You can get the size of the List by len(List) . Here list is a keyword for generating a List.

Or you may use an alternative :


n = int(input())    # Number of elements

List = [ int(elem) for elem in input().split(" ")  ]

If you want it as List of strings, then use :


List = list( input().split(" ") )

or

s = input()   # default input is string by using input() function in python 2.7+

List = list( s.split(" ") )

Or

List = [ elem for elem in input().split(" ")  ]

Number of elements count is necessary while using a loop for receiving input in a new line ,then


Let the Input be like :

5

1

2

3

4

5

The modified code will be:-


n = int(input())

List = [ ]  #declare an Empty list

for i in range(n):

    elem = int(input())

    List.append ( elem )

For Earlier version of python , use raw_input ( ) instead of input ( ), which receives default input as String.