In its simplest form, the for loop and the if command take up at least three lines and two indents. If you write them in one line - it speeds up the program? Or just gives a more readable form and reduces the number of lines, but there is no practical use? PS nobody reads my code anymore)

1 answer 1

On large amounts of data, list comprehension usually works faster than simple for ... loop :

An example for a list with 10,000,000 items:

 In [51]: lst = list(range(10**7)) In [52]: %%timeit ...: res = [] ...: for x in lst: ...: if x % 3 == 0: ...: res.append(x) ...: 2.26 s ± 55.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [53]: %%timeit ...: res = [x for x in lst if x % 3 == 0] ...: 1.66 s ± 6.87 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 
  • How can I change your code to run it in jupyter notebook? And what did you launch it with? - Alex Sapsay
  • I tried hard to understand the article from the first commentator, I wanted to understand why the generators have faster time to work with the list than through the cycle of the form. But I did not understand. until my level of knowledge allows. Could you explain very much on the fingers what is the idea of ​​such a win? - Alex Sapsay
  • one
    @AlexSapsay, I ran all the code in iPython (interactive Python is the console equivalent of Jupyter). “In [XX]” is “prompt”, it is not necessary to launch it - MaxU
  • one
    @AlexSapsay, a nice comparison here - MaxU September
  • one
    @AlexSapsay, no, this is not the same thing. Here more details about the differences ... - MaxU