0

learn python by myself. I made a function for filling list. But I have 2 variants, and I want to discover which one is better and why. Or they both awful anyway I want to know truth.

def foo (x):
    l = [0] * x
    for i in range(x):
        l[i] = i
    return l

def foo1 (x):
    l = []
    for i in range(x):
        l.append(i)
    return l
1
  • 6
    I would say the second is more idiomatic and can be easily translated to a list-comprehension. But in this particular case you can actually just do list(range(x))... Commented Mar 25, 2020 at 13:42

1 Answer 1

1

from a performance perspective the first version foo is better:

%timeit foo(1000000)
# 52.4 ms ± 1.99 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit foo1(1000000)
# 67.2 ms ± 916 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

but the pythonic way to unpack an iterator in a list will be:

list(range(x))

also is faster:

%timeit list(range(1000000))
# 26.7 ms ± 661 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.