6

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?

1
  • Why you didn't do like that i / 100.0. And why you make float from float in float(0.9)? Commented Nov 28, 2013 at 9:05

9 Answers 9

14

[] 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.

Sign up to request clarification or add additional context in comments.

Comments

3

Use the itertools module:

In [8]: for i in itertools.count(0.9, 0.01):
   ...:    print i
   ...:    if i > 1.2:
   ...:        break
   ...:     
0.9
0.91
0.92
0.93
.
.
.
1.18
1.19
1.2

As pointed out in the comments, the count() can be combined with a takewhile in order to create a list-comprehension:

[i for i in itertools.takewhile(lambda x: x <= 1.2, itertools.count(0.9, 0.01))]

2 Comments

itertools.count is a useful starting point, but I'd wrap it in itertools.takewhile(lambda x: x <= 1.2, itertools.count(0.9, 0.01))
+1 for an alternative way of doing it. Itertools is packed with goodness and it's always great to ensure people hear about it.
3

You need to extend the list. Use:

l.append(init + (float(i)/100))

or

l += [init + (float(i)/100)]

or even the more pythonic way

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

1 Comment

You mean append instead of extend
1

Consider appending the values to the list using l.append(), like this:

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

Edit: There is another way to do this, without using any list functions and just the random function (although the previous method is probably easier). Basically, you just create a random list and then replace the values in the list with the required values. Take a look:

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

It should work this way as well. But, this is only if you don't want to use any list functions. Still, the first script is easier and probably better.

1 Comment

Gah. Don't use random to prefill a list! It doesn't matter for a short list like this, but calls to random.random() are somewhat time-consuming. Use None or 0 as a placeholder. And you can create the list directly using multiplication: [None] * 31
0

You cannot assign values to list on indexes which do not exist:

>>> abc = []
>>> abc[0] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

Use append , which appends the value in the list i.e. assigns it to the next index.

Or this can also be easily done using list comprehension:

>>> [ round(float(0.9) + (float(i) / 100 ),2) for i  in range(0,31)]
[0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0, 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08, 1.09, 1.1, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.2]

Note: I have used round to round everything up to 2 decimal digits. You can remove that part, if you don't need it.

Comments

0

Unless I am overlooking something, you can do this with a list comprehension:

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

Whatever solution you end up using, consider floating point error and maybe use the decimal.Decimal class instead of floats. All solutions I tested with floating points produced rounding errors, eg:

>>> l
[0.9, 0.91, 0.92, 0.93, 0.9400000000000001, ...]

Comments

0

About .append() you already was informed.

But there is another point: Due to the fact that .01 cannot be represented in floatin point exactly, keeping on adding .01 will sum up this error.

More exact would be to do

init = float(0.9)
end = float(1.21)
steps = 31

l = []
for i  in range(0,31):
    l.append((init * (steps - i) + end * i) / steps)

Comments

0

Try This- :

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

It will work :)

Comments

0

Everyone has given great answers however I thought why not a general function to solve this problem i.e without knowing the range in advance (in this case range is 0-31)

>>> l=[]

>>> def addNumFun(startRange, endRange, interval):
          init = str(interval)[::-1].find('.')
          start = int(startRange * (10**init))
          end = int(endRange * (10**init))     
          for i in range(start,end):
             l.append(i/(10**init))
          l.append(end/(10**init))        # to add the last number of range

>>> addNumFun(0.9,1.2,0.01)
>>> l
[0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0, 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08, 1.09, 1.1, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.2, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0, 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08, 1.09, 1.1, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.