abcdef
abcdef

Reputation: 349

decimal range in for

Sorry for my beginner question. I want to construct decimal range step in for cycle using the following construction:

max_value = 10
my_range = [r * 0.01 for r in range(0, max_value) ]
    for i in range ( my_range ): //Error
         print (i)

But there is the following error:

TypeError: 'list' object cannot be interpreted as an integer

Upvotes: 0

Views: 460

Answers (3)

orip
orip

Reputation: 75427

Try

for i in my_range:
  print(i)

You've create the my_range list, which you can iterate over with for. You don't need to call range() again.

The range() function accepts integers as parameters, but running range(my_range) passes in your list, which results in this error.

Upvotes: 0

Zaur Nasibov
Zaur Nasibov

Reputation: 22659

The error appears because range() function accepts three arguments: starting value (included in iteration), end value (not included) and a step. From mathematical point of view, it's: [a1, a2, ... an) where d = a2 - a1 is the step.

So, my_range = [r * 0.01 for r in range(0, max_value) ] creates a list. And naturally, range() can't accept a list as an argument.

In case, if you need [0.01, 0.02, ... 10]:

step = 0.01
max_val = 10
for i in range(0, max_val / step + 1):
    print i * step

Upvotes: 1

Keith
Keith

Reputation: 43024

Your my_range is already a list. Just do:

for i in my_range:
    print(i)

Upvotes: 3

Related Questions