Search code examples
pythonlistmatplotlibgenerator

The most pythonic way to make a list / a generator with limits


I would like to plot a function in matplotlib, but only in a range bounded by two floats, say 2.6 and 8.2. For that I need a list or a generator that includes two float bounds, such as

[2.6, 3, 4, 5, 6, 7, 8, 8.2]

I know this can be done like this

lst = [2.6]
lst.extend(list(range(ceil(2.6), ceil(8.2))))
lst.append(8.2)

but this is very quirky. Is there any better pythonic way to do that?


Solution

  • PEP 448's additional unpacking generalizations make this at least a little less verbose:

    lst = [2.6, *range(ceil(2.6), ceil(8.2)), 8.2]
    

    I'd personally wrap it in a function and document what/why you do this, but it works fine inlined, assuming the code makes more sense in context than it does lacking context here.

    If lazy generation (single pass, no in-memory collection) is acceptable/desirable, you can use itertools.chain to make an iterator producing the same values:

    from itertools import chain
    
    gen = chain([2.6], range(ceil(2.6), ceil(8.2)), [8.2])
    

    If the values being provided might themselves be even integers, you may want to use math.nextafter to ensure the range bounds don't overlap the start point, changing the range to:

    range(ceil(math.nextafter(2.6, math.inf)), ceil(8.2))
    

    for either solution above.


    As a side-note, the list call in your original code was redundant; .extend takes any iterable, as does the list constructor, so if you can convert it to a list in the first place, you could pass it to extend directly and avoid the temporary list.