简体   繁体   中英

Iterate 2 lists of same length; create a list of n consecutive numbers without using generators

I have seen questions asking about creating a list of N numbers in python. Say an input N = 6 should create [0,1,2,3,4,5]. All answers I saw had the range function. Now I am using Python 3. On executing the range function to create a list, I have seen that code executes slowly, popping 1 digit at a time because range is a generator function.

Is there an alternative to create a list of consecutive numbers(assuming a very large one) that doesn't use a generator function like range so that there is no slow down? I can use a C type approach of checking if n < N but is there a more Pythonic way of doing it?

Please run this code in IDLE to understand my question more clearly:

x = list(range(14))
for n in x:
    print(n)

In general, using generators is the Pythonic way to do it. Generators tend to be very fast in Python. Let's start by just looking at different ways of creating a precomputed list of N integers:

import timeit

print(
    "Generating list from range:",
    timeit.timeit("list(range(100))")
)
print(
    "Generating list with comprehension:",
    timeit.timeit("[i for i in range(100)]")
)
print(
    "Generating list with while:",
    timeit.timeit(
        """\
i = 0
res = []
while i < 100:
    res.append(i)
    i += 1"""
    )
)

On my system (with Python 3.5.2), this gives:

Generating list from range: 1.0031339479999133
Generating list with comprehension: 3.2253709860001436
Generating list with while: 12.400529407000022

So, just directly converting the range object to a list gives the best performance if you're just trying to create a precomputed list of N integers. Now, let's see what happens when iterating on a precomputed list vs. iterating on a range object:

print(
    "Precomputed range:",
    timeit.timeit(
        '[x for x in seq]',
        setup='seq = range(100)'
    )
)

print(
    "Precomputed list:",
    timeit.timeit(
        '[x for x in seq]',
        setup='seq = list(range(100))'
    )
)

On my system, this yields

Precomputed range: 3.063208956000153
Precomputed list: 3.0270772009998836

The performance difference from iterating on a range object vs. a precomputed list is negligible. So, in general, I would give preference to just using a range object if you need an iterable with N integers, regardless of performance considerations.

My bad. I checked and found that the delay I was talking about was not because of using the generator. It looks like IDLE executes the print statement slowly as compared to my IDE PyCharm. In Pycharm, all the output is printed together and instantly.

The same code runs much slower in IDLE compared to Pycharm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM