Python Forum

Full Version: joined ranges
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
given 4 ints which define 2 ranges, i can do
foo = [x for x in range(a,b)]+[x for x in range(c,d)]
but it would be nice if there was a more compact form like
foo = range(a,b,1,c,d,1) # warning: invalid code
anyone know of a compact way to join multiple ranges preferably in a range-like object? otherwise, i'm thinking of making a generator to do this.
There is
foo = itertools.chain(range(a, b), range(c, d))
the idea i had, but now no longer care to do was a generator like ranges((aa,az[,ai]),(ba,bz[,bi]),...).
Isn't this something a list comprehension can easily solve?

>>> ranges = lambda a, b: (i for items in (a, b) for i in items)
>>> ranges(range(2, 9, 2), range(5))
<generator object <lambda>.<locals>.<genexpr> at 0x031EC450>
>>> list(ranges(range(2, 9, 2), range(5)))
[2, 4, 6, 8, 0, 1, 2, 3, 4]
(Apr-03-2018, 06:30 PM)nilamo Wrote: [ -> ]Isn't this something a list comprehension can easily solve?
Have a look at itertools.chain()