What is the fastest way to initialize an integer array in python?

前端 未结 6 386
终归单人心
终归单人心 2020-12-11 06:57

Say I wanted to create an array (NOT list) of 1,000,000 twos in python, like this:

array = [2, 2, 2, ...... , 2]

What would be a fast but simple

6条回答
  •  一整个雨季
    2020-12-11 07:18

    Using the timeit module you can kind of figure out what the fastest of doing this is:

    First off, putting that many digits in a list will kill your machine most likely as it will store it in memory.

    However, you can test the execution using something like so. It ran on my computer for a long time before I just gave up, but I'm on an older PC:

    timeit.Timer('[2] * 1000000').timeit()
    

    Ther other option you can look into is using the array module which is as stated, efficient arrays of numeric values

    array.array('i', (2 for i in range(0, 1000000)))
    

    I did not test the completion time of both but I'm sure the array module, which is designed for number sets will be faster.

    Edit: Even more fun, you could take a look at numpy which actually seems to have the fastest execution:

    from numpy import *
    array( [2 for i in range(0, 1000000)])
    

    Even faster from the comments:

    a = 2 * ones(10000000)
    

    Awesome!

提交回复
热议问题