PKlumpp
PKlumpp

Reputation: 5233

Generators in python

I just came across the problem that I could not use the built-in range() function of python for float values. So I decided to use a float-range function that I manually defined:

def float_range(start, stop, step):
    r = start
    while r < stop:
        yield r
        r += step

Problem is: This function returns a generator object. Now I needed this range for a plot:

ax.hist(some_vals, bins=(float_range(some_start, some_stop, some_step)), normed=False)

This will not work due to the return type of float_range(), which is a generator, and this is not accepted by the hist() function. Is there any workaround for me except not using yield?

Upvotes: 0

Views: 138

Answers (2)

Davidmh
Davidmh

Reputation: 3865

You can convert a generator to a list using:

list(float_range(1, 4, 0.1))

But seeing you are using matplotlib, you should be using numpy's solution instead:

np.arange(1, 4, 1, dtype=np.float64)

or:

np.linspace(start, stop, (start-stop)/step)

Upvotes: 1

Ashalynd
Ashalynd

Reputation: 12563

If you need to give a range, you can do either

ax.hist(some_vals, bins=(list(float_range(some_start, some_stop, some_step))), normed=False)

Or just make your float_range return a list:

def float_range(start, stop, step):
    result = []
    r = start
    while r < stop:
        result.append(r)
        r += step
    return result

BTW: nice reference on what you can do with generators in Python: https://wiki.python.org/moin/Generators

Upvotes: 3

Related Questions