Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic python: how to increase value of item in list

Tags:

python

This is such a simple issue that I don't know what I'm doing wrong. Basically I want to iterate through the items in an empty list and increase each one according to some criteria. This is an example of what I'm trying to do:

list1 = []
for i in range(5):
    list1[i] = list1[i] + 2*i

This fails with an list index out of range error and I'm stuck. The expected result (what I'm aiming at) would be a list with values:

[0, 2, 4, 6, 8]

Just to be more clear: I'm not after producing that particular list. The question is about how can I modify items of an empty list in a recursive way. As gnibbler showed below, initializing the list was the answer. Cheers.

like image 653
Gabriel Avatar asked Dec 01 '22 19:12

Gabriel


2 Answers

Ruby (for example) lets you assign items beyond the end of the list. Python doesn't - you would have to initialise list1 like this

list1 = [0] * 5
like image 79
John La Rooy Avatar answered Dec 07 '22 22:12

John La Rooy


So when doing this you are actually using i so you can just do your math to i and just set it to do that. there is no need to try and do the math to what is going to be in the list when you already have i. So just do list comprehension:

list1 = [2*i for i in range(5)]

Since you say that it is more complex, just don't use list comprehension, edit your for loop as such:

for i in range(5):
    x = 2*i
    list1[i] = x

This way you can keep doing things until you finally have the outcome you want, store it in a variable, and set it accordingly! You could also do list1.append(x), which I actually prefer because it will work with any list even if it's not in order like a list made with range

Edit: Since you want to be able to manipulate the array like you do, I would suggest using numpy! There is this great thing called vectorize so you can actually apply a function to a 1D array:

import numpy as np
list1 = range(5)
def my_func(x):
    y = x * 2
vfunc = np.vectorize(my_func)
vfunc(list1)
>>> array([0, 2, 4, 6, 8])

I would advise only using this for more complex functions, because you can use numpy broadcasting for easy things like multiplying by two.

like image 37
Ryan Saxe Avatar answered Dec 07 '22 22:12

Ryan Saxe