Shaun Barbour
Shaun Barbour

Reputation: 49

How to iterate through a list of integers with a step that is a float?

I've been searching the web for over an hour. I cannot find help on this one.

Instructions: Make a list called possible_ms that goes from -10 to 10 inclusive, in increments of 0.1.

When I create the list and try to iterate over it by increments of .1, I get: TypeError: 'float' object cannot be interpreted as an integer.

So then, I make all the integers floats, still does not work.

Finally, after over an hour, I click to show the solution. It also does not make sense.

Solution: possible_ms = [m * 0.1 for m in range(-100, 101)]

Can someone please explain this logic to me? Is it when you multiply the .1 times 91, you get 9.1? So maybe with the .1 multiplier through a range of -100 to 100, it reduces it to -10 to 10 and allows the .1 to go through it? Yes? No?

Upvotes: 2

Views: 549

Answers (1)

Mauricio Loustaunau
Mauricio Loustaunau

Reputation: 129

The solution you explain is perfect Shaun :). I will give you my review and hope it helps

  1. Array creation through list comprehension is cool but you don't want to achieve cool in programming, you want to achieve readability and good practices (again, I emphasise that it is perfectly valid) (this is not only my opinion, it is stated on the Introduction to Computation and Programming Using Python, MIT book page 64 under the title "List comprehension"). Maybe if you see it in regular notation you may understand it better

    for m in range (-100, 101):
        print(m*0.1)
    

    As you explained in your solution you have to iterate form -10 to 10 in steps of 0.1. Iterating in floats steps on python is not possible. That is why the solution extends the range to -100, 100 and multiply it by 0.1 to allow it to travel the way it is asked. You were right in your explanation. Hope it helped and learned something else about good practices and readability (always remember that your code is not only coded for a solution, but also for other programmers that are going to work with it), if you have any other doubt, don't hesitate to ask it :)

Upvotes: 3

Related Questions