Menu

List Comprehension vs for Loop in Python 3.13: I Timed 14 Versions, the Loop Body Decides
📰

List Comprehension vs for Loop in Python 3.13: I Timed 14 Versions, the Loop Body Decides

DEV Community: beginners·Blogs World·about 5 hours ago
#Ps8EgPoZ
#devtobeginners#devto#dev#loop#list
Reading 0:00
15s threshold

"Use a list comprehension, it's faster" is one of the first Python performance tips people learn. It's true, but on a current Python the gap is smaller than most people expect, and in some cases it disappears completely.

I timed the same work written in different ways on Python 3.13.5 over a list of 1,000,000 integers. Each number below is the best of 5 repeats of 5 runs each, using timeit , on one Linux machine. Your absolute numbers will be different. The ratios between them are what matter.

The setup

import timeit

setup = "data = list(range(1_000_000))"

loop = """ out = [] for x in data: out.append(x * 2) """

comp = "[x * 2 for x in data]"

for name , stmt in [ ( "for + append" , loop ) , ( "list comprehension" , comp ) ] : t = min ( timeit .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.