Skip to content Skip to sidebar Skip to footer

Create Variable Whose Size Increases Inside A For Loop

I have a for loop which does a logical computation on the rows of a large matrix and determines if each row is 'good' or 'bad'. If it is good, then I want to make a copy of this ro

Solution 1:

You need to create a list with the proper length before assigning to it:

store = [0] * len(x)

But to tell the truth, that's not the most idiomatic way to traverse and fill a list in Python, this looks better:

store = []
for e in x
    a = function(e)
    ifa == 1
        store.append(e)

Or even better, let's use a list comprehension:

store = [e for e in x if function(e) == 1]

Solution 2:

If a list/ variable store is not defined prior to using it, Python raises an error. So, define store with

store = []

And use store.append(i).

Post a Comment for "Create Variable Whose Size Increases Inside A For Loop"