Skip to content

Comment on Python: copying a list the right wayparent

Comments

Can you explain why `[:]` is faster for small list (10 elements) but `list()` is faster for larger list (100000 elements).

    ~$ python -S -mtimeit -s "a = list(range(10))" "a[:]"
    1000000 loops, best of 3: 0.198 usec per loop
    ~$ python -S -mtimeit -s "a = list(range(10))" "list(a)"
    1000000 loops, best of 3: 0.453 usec per loop
    ~$ python -S -mtimeit -s "a = list(range(100000))" "a[:]"
    1000 loops, best of 3: 675 usec per loop
    ~$ python -S -mtimeit -s "a = list(range(100000))" "list(a)"
    1000 loops, best of 3: 664 usec per loop
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.