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

I get the input values ​​in a list using the following statement:

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

However, I would like to limit the number of inputs that the user can give at a time. For example, if the limit is specified by the number n, the array should display only the first n values ​​entered during the program.

for example: if n = 6, Input:

 1 2 3 4 5 6 7 8 9 10 

When executing 'print ar', it should display the following without error messages:

 [1, 2, 3, 4, 5, 6] 
+6
source share
2 answers

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

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

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

This slightly improves performance. We can also make simple - ar = map(int, raw_input().split())[:n] , but it will be less productive 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] 
+4
source

How about indexing ar only for the 6th element? Technically, this is for the 7th element, since newarray will cut to, but not including the nth element

 ar = map(int, raw_input().split()) print ar #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] newarray=ar[0:6] print newarray #[1, 2, 3, 4, 5, 6] 

This should allow unlimited input.

+1
source

All Articles