How to take input in one line for array and its length in python

Viewed 1013

i want to take input as

3 10 20 30 

i.e, n array elements

I tried -

n , arr = int(input()), list(map(int(input).split()[:n]))

It shows error as n is not defined

2 Answers

Think about how Python interprets your statement:

  1. it evaluates the r-value (the right-hand-side part of the assignment), which is a tuple, then
  2. assigns that tuple to the l-value: (n, arr).

But in step 1, it encounters a yet-unknown quantity: n.

You would therefore do, instead (and assuming s = '3 10 20 30', as it isn't a good idea to shadow the built-in function input()):

arr = [int(x) for x in s.split()]
n = len(arr)  # if you really need it

Edit

It has been pointed out that the expected result may be n: 3 and arr: [10, 20, 30]. If that is indeed the case:

n, *arr = [int(x) for x in s.split()]
Related