Best and/or fastest way to create lists in python

Viewed 63559

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

Simple loop with append:

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

Simple loop with +=:

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 don't think there would be any performance difference given that the lists have only 50 elements, but what if I need a list of a million elements? Would the use of xrange make any improvement? Which is the preferred/fastest way to create and initialize lists in python?

4 Answers

If you want to create a list incrementing, i.e. adding 1 every time, use the range function. In range the start argument is included and the end argument is excluded as shown below:

list(range(10,20))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

If you want to create a list by adding 2 to previous elements use this:

list(range(10,20,2))
[10, 12, 14, 16, 18]

Here the third argument is the step size to be taken. Now you can give any start element, end element and step size and create many lists fast and easy.

Thank you..!

Happy Learning.. :)

Related