levio_sa
levio_sa

Reputation: 145

Append to Empty list vs Initialising First and then giving values to list indexes

I'm trying to make a code in python. I know beforehand the size of list.

Suppose list is l and its size is n.

So should I first initialise a list of length n and then using a for loop put l[i]=i for i from 0 to n.

OR

Is it better to first initialise empty list and then usinig a for loop append items into the list?

I know that both the two approaches will yield the same result. I just mean to ask if one is faster or more efficient than the other.

Upvotes: 1

Views: 1035

Answers (3)

swademc
swademc

Reputation: 1

I got the opposite result compared to another answer.

import time

count = 10000000

def main1():
    x = [None]*count
    for i in range(count):
        x[i] = i

def main2():
    y = []
    for i in range(count):
        y.append(i)


start_time = time.time()
main1()
end_time = time.time()
print("1:", end_time-start_time) # 0.488

start_time = time.time()
main2()
end_time = time.time()
print("2:", end_time-start_time) # 0.728

Upvotes: 0

user12460811
user12460811

Reputation:

If you now the size of your list your first approach is correct. you can use numpy library to make your list with any size you want.

import numpy as np
X = np.zeros(n, y) #size of your list
#use your for loop here
for i in range(10):
    a[i] = i+1
X.tolist()

Upvotes: 0

Noam Hudson
Noam Hudson

Reputation: 151

Appending is faster because lists are designed to be inherently mutable. You can initialise a fixed-size list with code like

x = [None]*n

But this in itself takes time. I wrote a quick program to compare the speeds as follows.

import time
def main1():
    x = [None]*10000
    for i in range(10000):
        x[i] = i
    print(x)

def main2():
    y = []
    for i in range(10000):
        y.append(i)
    print(y)


start_time = time.time()
main1()
print("1 --- %s seconds ---" % (time.time() - start_time))
#1 --- 0.03682112693786621 seconds ---
start_time = time.time()
main2()
print("2 --- %s seconds ---" % (time.time() - start_time))
#2 --- 0.01464700698852539 seconds ---

As you can see, the first way is actually significantly slower on my computer!

Upvotes: 1

Related Questions