7
\$\begingroup\$

I have 2 inputs: 1 single number and some numbers separated by whitespace:

1
1 2 3 4 5

I want to loop over the second input, and I don't need the first input. I did this, which works:

input()
for x in input().split():somecode()

But can I go directly to the second input without doing the input() at the beginning or with shorter code?

I tried this code (-2 bytes) but it doesn't work, it needs two input() to work:

a,b=input()
for x in b.split():somecode() #Error : not enough values to unpack (expected 2, got 1)

a,b=input(),input()
for x in b.split():somecode() #OK
\$\endgroup\$
3
  • 1
    \$\begingroup\$ If you're using print only once in the somecode section, it might be useful to assign input to a variable and use that to print the output as well. This saves one byte over the open(0) method, but has conditions to use it \$\endgroup\$
    – Jo King
    Jul 30, 2021 at 16:13
  • \$\begingroup\$ Is this in Python 2 or 3? \$\endgroup\$
    – xnor
    Jul 30, 2021 at 20:29
  • \$\begingroup\$ @xnor 3, and thank you for editing \$\endgroup\$
    – Basto
    Jul 30, 2021 at 20:34

2 Answers 2

16
\$\begingroup\$

open(0), 40 bytes

The builtin function open returns a file object which can be iterated over, line by line. Usually you pass a path to open, but it also takes file descriptor, which are integers that refer to special files.

0 is the file descriptor for the standard input (source), and this allows you to open the input as file with open(0).

Converting this file to a list (of lines) and accessing the second entry saves 3 bytes in this case:

for x in[*open(0)][1].split():somecode()

Other than input() this does not remove trailing newline characters (\n), but in this case split takes care of it. Another downside is that you can not combine input() and open(0). The same technique often helps when you need to read multiple lines of input, example:

# a is the first line of input, b the seconds and r contains all remaining lines.
a,b,*r=open(0)
\$\endgroup\$
4
\$\begingroup\$

Python 3, 42 bytes

You can use open(0) to read all the inputs in once and unpack them.

_,a=open(0)
for i in a.split():somecode(i)

Try it online!

if the inputs contains more than two lines you can also use:

_,*a=open(0)

Try it online!

but it will append a trailing newline to all the elements but the last

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.