I want to read a list of IDs (as integers) from a file in Python3. The file has a single ID per line and no blank lines.

with open(file_eval_id) as f:
    eval_ids = [list(map(int, line.split()))[0] for line in f]

Is there a cleaner way of doing it? I have doubts about referencing the list(...)[0] as the best way.


1 Answer 1


You can use something like the following:

with open(file_eval_id) as f:
    eval_ids = [int(line) for line in f]

The code assumes, that ID is the only thing in the line.

  • 2
    \$\begingroup\$ You probably don't even need to .strip(). \$\endgroup\$ Oct 8, 2017 at 14:42
  • 1
    \$\begingroup\$ Since there is only one ID per line, there is no need to use the .strip() \$\endgroup\$ Oct 8, 2017 at 17:05
  • \$\begingroup\$ Yes, true. int will discard the end of line. \$\endgroup\$
    – Roman Susi
    Oct 8, 2017 at 17:36

Your Answer

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

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