You can use itertools.chain, breaking each line and matching with ints:
from itertools import chain with open("in.txt") as f: print(list((map(int,chain.from_iterable(line.split() for line in f))))) [1, 19, 15, 36, 23, 18, 39, 2, 36, 23, 4, 18, 26, 9, 3, 35, 6, 16, 11]
For python2, use itertools.imap instead of a map. using a chain with a map and itertools.chain avoids immediately reading the entire file into memory, which .read will do.
Some timings for python3 in the file are the same as your input * 1000:
In [5]: %%timeit with open("ints.txt","r") as f: list(map(int,re.split(r"\s+",f.read()))) ...: 100 loops, best of 3: 8.55 ms per loop In [6]: %%timeit with open("ints.txt","r") as f: list((map(int, chain.from_iterable(line.split() for line in f)))) ...: 100 loops, best of 3: 5.76 ms per loop In [7]: %%timeit ...: with open("ints.txt","r") as f: ...: [int(i) for i in f.read().split()] ...: 100 loops, best of 3: 5.82 ms per loop
So itertools matches the comp list, but uses a lot less memory.
For python2:
In [3]: %%timeit with open("ints.txt","r") as f: [int(i) for i in f.read().split()] ...: 100 loops, best of 3: 7.79 ms per loop In [4]: %%timeit with open("ints.txt","r") as f: list(imap(int, chain.from_iterable(line.split() for line in f))) ...: 100 loops, best of 3: 8.03 ms per loop In [5]: %%timeit with open("ints.txt","r") as f: list(imap(int,re.split(r"\s+",f.read()))) ...: 100 loops, best of 3: 10.6 ms per loop
The comp list is a little faster, but uses more memory again if you are going to read everything into memory using the read split imap approach is again the fastest:
In [6]: %%timeit ...: with open("ints.txt","r") as f: ...: list(imap(int, f.read().split())) ...: 100 loops, best of 3: 6.85 ms per loop
Same thing for python3 and map:
In [4]: %%timeit with open("ints.txt","r") as f: list(map(int,f.read().split())) ...: 100 loops, best of 3: 4.41 ms per loop
So, if speed is all you need, use the list(map(int,f.read().split())) or list(imap(int,f.read().split())) .
If memory is also a concern, combine it with a chain. Another advantage of the chain approach, if memory is a concern, is if you pass int functions or iterate over, you can pass the chain object directly so you don't need to store all the data in memory at all.
The last little optimization is to map str.split in a file object:
In [5]: %%timeit with open("ints.txt", "r") as f: list((map(int, chain.from_iterable(map(str.split, f))))) ...: 100 loops, best of 3: 5.32 ms per loop