Medulla Oblongata
Medulla Oblongata

Reputation: 3961

Python append to array vs replace array of zeros

In Python, when calculating something in a for loop, it is possible to either append the solution from each iteration to a list, eg.

import numpy as np

steps = 100
x_list = np.linspace(0,2.0,steps)

y_list = []

for x in x_list:

    # perform calculations, iterating over values in x_list
    # final solution is z:
    #z = ...

    y_list.append(z)

or create an array of zeros and replace each zero with the solution from each iteration, eg.

import numpy as np

steps = 100
x_list = np.linspace(0,2.0,steps)

y_list = np.zeros(steps)

for x in x_list:

    # perform calculations, iterating over values in x_list
    # final solution is z:
    #z = ...

    y_list[x] = z

In general, which method is more efficient or "Pythonic"? Or does it really depend on the calculation inside the for loop itself?

Upvotes: 0

Views: 2384

Answers (1)

Chemik
Chemik

Reputation: 1479

I would say none (or both).

More "pythonic" solution (and also more, let say, "programathic") is to write function that does the calculation and use list comprehensions

def calculator( x ):
    """calculation"""
    return result

y_list = [calculator(x) for x in x_list]

Upvotes: 2

Related Questions