Creating a list using a loop, filling it with float()

for-loop, list, python

Solution

`[]` works only if there is an element already at this index the list. Use list.append():

init = float(0.9)
l = []
for i  in range(0,31):
  l.append(init + ( float(i) / 100 ))

Once you are confortable with this, you can even use a comprehension list :

l = [init + (float(i) / 100 )) for i in range(0, 31)]

It is very rare in Python to use indexes. I understand a lot people do it because it's an habit in other languages, but most of the time, it's an anti-pattern in Python. If you you see a `i` somewhere, always wonder if you are not trying to reinvent the wheel.

BTW. Division has priority on addition so no need for parenthesis. Plus, `init = float(0.9)` is redundant. you can write `init = 0.9`. And the `/` always returns a float, therefor you can do :

l = []
for i in range(0, 31): 
  l.append(0.9 + i / 100)

Also note the way I place spaces. It's the most used style convention in Python.

And with a comprehension list :

l = [0.9 + i / 100 for i in range(0, 31)]

It is a much simpler way to achieve what you want. Don't worry, if your code works and you understand it, it's the most important. You don't NEED to do this. I'm just giving you this information so you can use it later if you wish.

Problem

I'm currently working on a project that requires me to have a list from 0.9 to 1.2 with steps of 0.01. I tried the following: ``` init = float(0.9) l = [] for i in range(0,31): l[i]= init + ( float(i) / 100 ) ``` However, python gives me the following output: Traceback (most recent call last): File "", line 2, in IndexError: list assignment index out of range Can anyone help me solve this problem?

Original source