6

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]
1
  • And it should ignore the rest of the input? Commented Oct 14, 2015 at 4:14

3 Answers 3

5

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]
Sign up to request clarification or add additional context in comments.

5 Comments

Bravo! Thanks, that's a quite elegant solution, just what I wanted. I'm quite new to python, and slicing is quite a fresh concept for me.
Actually I found that using the statement: 'ar = map(int, raw_input().split())[:n] ' works as well. Arguments don't have to be provided for the split() function call.
Yes, I have explained that in my answer. My first solution was that. But then for a bit more performance I gave the current solution.
With simple slicing like that you would be taking all the numbers in the input , splitting them all, and then converting them all to int before slicing and getting the first n results.
Ah ok, can't see how I missed that!
1

How about indexing ar to just the 6th element? Technically, it's to the 7th element, as newarray will slice up to, but not including 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 for unlimited input

Comments

0

I was looking for a solution to the same question.

I figured out what I can do below is my solution.

bookid = []
M = int(input())
S = input().split()
for i in range(M):
    books.append(S[i])
print(booksid)

But I think it's definitely not the most effective way to do it but easy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.