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
Think about how Python interprets your statement:
tuple, thentuple 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()]
s = '3 10 20 30' then OP wants n = 3, arr = [10, 20, 30]n against the number of elements after that.Using Python 3.8+ this can be solved quite elegantly by using assignment expressions:
n, arr = int((v := input().split())[0]), list(map(int, v[1:]))
len(v := input().split()[1:]), list(map(int, v))
arr = list(map(int, input().split()))[1:]nandarr?