Create a list of the best in python and / or the quickest way

In python, as far as I know, there are at least 3-4 kinds of ways to create and initialize a list given size:

Simple cycle append:

my_list = [] for i in range(50): my_list.append(0)

Simple cycle +=:

my_list = [] for i in range(50): my_list += [0]

List comprehension:

my_list = [0 for i in range(50)]

List and integer multiplication:

my_list = [0] * 50

In these examples, I think the only list any performance difference is only 50 elements there, but if I need one million contains a list of elements it? Use xrangewhat improvements it? Preferred / Which is the quickest way to create and initialize a list in python?

 

solution


Let's run some time tests *  :timeit.timeit

>>> from timeit import timeit >>> >>> # Test 1 >>> test = """ ... my_list = [] ... for i in xrange(50): ... my_list.append(0) ... """ >>> timeit(test) 22.384258893239178 >>> >>> # Test 2 >>> test = """ ... my_list = [] ... for i in xrange(50): ... my_list += [0] ... """ >>> timeit(test) 34.494779364416445 >>> >>> # Test 3 >>> test = "my_list = [0 for i in xrange(50)]" >>> timeit(test) 9.490926919482774 >>> >>> # Test 4 >>> test = "my_list = [0] * 50" >>> timeit(test) 1.5340533503559755 >>>

As you can see, the last method is by far the fastest way.


However, it should be only a static items (e.g., integer) used. This is because it will create a list that contains a reference to the clause.

The following is a demonstration:

>>> lst = [[]] * 3 >>> lst [[], [], []] >>> # The ids of the items in `lst` are the same >>> id(lst[0]) 28734408 >>> id(lst[1]) 28734408 >>> id(lst[2]) 28734408 >>>

Such behavior is usually undesirable and can lead to errors in the code.

If you have a variable item (such as a list), then you should still use a list of very fast understanding:

>>> lst = [[] for _ in xrange(3)] >>> lst [[], [], []] >>> # The ids of the items in `lst` are different >>> id(lst[0]) 28796688 >>> id(lst[1]) 28796648 >>> id(lst[2]) 28736168 >>>

* Note: In all the tests, I replaced rangewas xrange. Since the latter returns an iterator, so it should always be faster than the former.

 

This article first appeared in Python black hole net , blog updated simultaneously Park

 

Guess you like

Origin www.cnblogs.com/pythonzhichan/p/11424759.html
Recommended