2

How to read an integer list from single line input along with a range in Python 3?

Requirement: reading integer values for a given list separated by a space from single line input but with a range of given size.

example:

Range = 4

Then list size = 4

Then read the input list from a single line of size 4

I tried below list comprehension statement, but it is reading a list from 4 lines [i.e creating 4 lists with each list representing values from a given line] instead of reading only 1 list with a size of 4

    no_of_marks = 4
    marksList = [list(int(x) for x in input().split()) for i in range(no_of_marks)]

Can someone help me in achieving my requirement?

2 Answers 2

1

You can use str.split directly, passing the no_of_marks for being maxsplit parameter:

no_of_marks = 4
res = [int(x) for x in input().split(" ", no_of_marks)] 

Here you have the live example

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, just like as I had expected. Thank you @Netwave!
@HarshaGV, glad to see it was helpful, please consider reading this so you can also collaborate: stackoverflow.com/help/someone-answers
1

Split the string, slice it to only take the first n words, and then turn them into integers.

marks = [int(x) for x in input().split()[:n]]

This will not fail if the input has fewer than n integers, so you should also check the length of the list

if len(marks) < n:
    raise ValueError("Not enough inputs")

1 Comment

this answer works as well.. can be used in case of list slices.. thank you @patrick-haugh

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.