Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting number of input values in an array/list in Python

I'm obtaining input values in a list using the following statement:

ar = map(int, raw_input().split())

However, I would want to limit the number of inputs a user can give at a time. For instance, if the limit is specified by a number n, the array should only capture the first n values entered during the program.

e.g: if n = 6, Input:

1 2 3 4 5 6 7 8 9 10

On performing 'print ar', it should display the following without any error messages:

[1, 2, 3, 4, 5, 6]
like image 477
Abhishek Tirkey Avatar asked Oct 14 '15 04:10

Abhishek Tirkey


People also ask

What is limit number in Python with example?

Limiting input number between minimum and maximum values range in Python. Raw. limit-number.py. def limit ( num, minimum=1, maximum=255 ): """Limits input 'num' between minimum and maximum values. Default minimum value is 1 and maximum value is 255.""". return max ( min ( num, maximum ), minimum)

What is the limit of input'NUM'in Python?

"""Limits input 'num' between minimum and maximum values. Default minimum value is 1 and maximum value is 255.""" Sign up for free to join this conversation on GitHub .

How to find minimum and maximum value in an array in Python?

Write a Python Program to Find Minimum and Maximum Value in an Array. The numpy module has min and max functions to return the minimum and maximum values in a numpy array. We use these numpy min and max functions to return the minimum and maximum values in the number and string array.

How to get a list of numbers as input in Python?

Example 1: Get a list of numbers as input from a user and calculate the sum of it Note: Python input () function always converts the user input into a string then returns it to the calling program. With those in mind, we converted each element into a number using an int () function.


1 Answers

If you want to ignore the rest of the input, then you can use slicing to take only the first n input. Example -

n = 6
ar = map(int, raw_input().split(None, n)[:n])

We are also using the maxsplit option for str.split so that it only splits 6 times , and then takes the first 6 elements and converts them to int.

This is for a bit more performance. We can also do the simple - ar = map(int, raw_input().split())[:n] but it would be less performant than the above solution.

Demo -

>>> n = 6
>>> ar = map(int, raw_input().split(None, n)[:n])
1 2 3 4 5 6 7 8 9 0 1 2 3 4 6
>>> print ar
[1, 2, 3, 4, 5, 6]
like image 79
Anand S Kumar Avatar answered Nov 01 '22 22:11

Anand S Kumar