0

You are given a set of integers separated by lines as input,for example....

7
2
4
5
8
9

but you want to get all these converted to a lst for your program, like [7,2,4,5,8,9] after several attempts, e.g.

nums = int (input())
lst = []
for i in nums:
    lst.append(int (i))
print (list)

Unfortunately, this outputs only the first element of the input [7] Even tried to use a range, no difference Please, what i am getting wrong?

Jai
  • 819
  • 7
  • 17
mko77
  • 25
  • 3

1 Answers1

0

input only returns one line. You would need to repeatedly call input to get each line, until input returns an empty string.

However, it's much easier to use the fileinput module, which can read either from standard input or from one or more files passed as arguments.

import fileinput

lst = [int(x) for x in fileinput.input()]

Then, if your numbers are in a file named numbers.txt, you can run your script with either

script.py < numbers.txt

to read the numbers from standard input, or

script.py numbers.txt

to have the fileinput module open the file and read from it directly. If fact, if you have multiple files, you could pass them all and fileinput would read them one after the other with the same loop:

script numbers.txt more_numbers.txt even_more_numbers.txt
chepner
  • 497,756
  • 71
  • 530
  • 681