Brain itch - python - how much faster are list comprehensions than for-loops

Benchmarking the 2 ways to loop over arrays

By Niraj Zade  |  2026 Sep 18  |  1m read  |  277 words  |  1 pages

Some time ago, I had an 1am brain itch:

If Python's for-loop is slow, and list-comprehension is fast - then by how much?

Ran a benchmark for this.

Each benchmark run processed an array of 1 million integers - once using for-loop, then once using list-comprehension.
1000 benchmark runs were performed sequentially - alternating between for-loop and list-comprehension in each run. This alternation spread the effect of things like thermal CPU throttling, core-switching etc evenly amongst both methods.

Result

The answer was: for python 3.10.12, list comprehension is faster by 10.46% on my machine. That's a huge difference.

So, moving the loop out of Python (for loop) and into CPython's optimized loop (via list comprehension) truly creates a tremendous performance improvement.

This is a graph of data from 1000 runs:

All python versions

Then, I ran the same benchmark for all major python versions. List comprehension is faster in all of them.

The results are:

  • 3.8.20 - faster by 13.51%
  • 3.9.25 - faster by 12.19%
  • 3.10.12 - faster by 10.96%
  • 3.11.14 - faster by 4.13%
  • 3.12.12 - faster by 2.85%

Interestingly, python 3.12 has almost closed the performance gap.

Quoting a comment by kirill-podoprigora, one of the core python devs, on linkedin: "You should run this benchmark on Python 3.12, since comprehensions are now inlined (see PEP 709), which makes them faster."

Here's a graph of data from 1000 runs in each python version:

Computer specs

OS: Ubuntu 24.04.4 LTS x86_64
Host: 21ECCTO1WW ThinkPad E14 Gen 4
Kernel: 6.8.0-139-generic
CPU: AMD Ryzen 5 5625U with Radeon G
GPU: AMD ATI 05:00.0 Barcelo
Memory: 38924MiB








Thoughts & opinions

Articles

I learn through writing, so I write a lot. Most of these are ever evolving pieces.


API
Data Engineering
Python
Resources
Work