2

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

3
  • Seems like you are trying to solve a challenge on one of these competitive programming sites. Let me give you a hint: Due to Python being a dynamic language (in simple terms) you don't need to care about the length of the "incoming" input array. Just do arr = list(map(int, input().split()))[1:] Commented Mar 5, 2021 at 11:46
  • what is the expected output for n and arr? Commented Mar 5, 2021 at 12:16
  • n should be 3 and arr=[10,20,30] Commented Mar 7, 2021 at 14:08

2 Answers 2

2

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

6 Comments

This gives the wrong output. If s = '3 10 20 30' then OP wants n = 3, arr = [10, 20, 30]
It's not clear from the question, but I can see that would be a plausible way to interpret it.
asterisk tuple packing/unpacking of your edit is the best solution, if you need to check n against the number of elements after that.
you should keep your answer as well: it's fun to see the walrus operator in action!
Yes, but in this case it's overkill and very hard to read. So far the only "useful" cases of assignment expressions I have found are conditionals.
|
1

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:]))

Obviously, you can just calculate n after the splitting and mapping as well, making the code much easier to read.

2 Comments

Nice! but I believe OP meant to len(v := input().split()[1:]), list(map(int, v))
Oh, yes, sorry.

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.