(Jul-27-2017, 05:36 AM)Skaperen Wrote: which is the better way to print a list of lines?
1. for line in lines:
print(line)
2. print('\n'.join(lines))
assuming there are not so many lines to eat up your memory.
I prefer the first option, if there are other things to do with the line like splitting, conversion, filtering etc.
If I don't do anything with the data, just saving it somewhere, I'll prefer the join method.
I think the function is not flushing automatically. Sometimes I had to use
flush=True
as argument inside the print function, when I was doing some asyncio tasks.
Please forget it to optimize first. They told us over the years that joining strings together is faster as using the operation for addition. This is not always True.
Make it first readable and later you can optimize.
Here an example:
first, second, third = 'Hello ', 'World', '!'
def str_concatination(first, second, third):
return first + second + third
def str_join(first, second, third):
return ''.join([first, second, third])
Output:
In [64]: %timeit str_concatination(first, second, third)
The slowest run took 8.33 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 145 ns per loop
Output:
%timeit str_join(first, second, third)
The slowest run took 8.48 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 195 ns per loop
The time varies from Python version to Python version. Internally there is a heavy optimization. The rule from the last years, that join is faster as the add operation, is not always True. In the IT-World we say: "Proof it" :-)
But please don't tell beginners that join is always faster.