You can use the built-in itertools module to take the cartesian product of all the range objects in A, and skip making B altogether:

import itertools
A = [range(2), range(4), range(3), range(3)]
list(itertools.product(*A))

Output (skipping some items for readability):

[(0, 0, 0, 0),
 (0, 0, 0, 1),
 (0, 0, 0, 2),
 (0, 0, 1, 0),
 (0, 0, 1, 1),
  .
  .
  .
 (1, 3, 2, 2)]

Verifying the length:

>>> len(list(itertools.product(*A)))
72

Note that itertools.product() yields tuple objects. If for whatever reason you'd prefer these to be lists, you can use a comprehension:

[[*p] for p in itertools.product(*A)]

Another approach, as @don'ttalkjustcode points out, is that you can avoid creating A entirely and skip directly to the cartesian product via the map() function:

list(itertools.product(*map(range, (2, 4, 3, 3))))

However, this assumes that all your ranges start at 0.

You could generalize this mapping technique by using a lambda which will create range objects from a list of tuples:

>>> list(map(lambda t: range(*t), ((6, -3, -1), (0, 3), (5,), (10, 1, -2))))
[range(6, -3, -1), range(0, 3), range(0, 5), range(10, 1, -2)]
Answer from ddejohn on Stack Overflow
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-convert-range-into-a-set
Convert Range into a Set
# Take a range myrange = range(4, 15, 2) # Convert range object into a set myset = set(myrange) print(myset) ... In this tutorial of Python Ranges, we learned how to convert a range object into a Set of integers using set() builtin function.
๐ŸŒ
Machinelearninghelp
machinelearninghelp.org โ€บ programming-for-machine-learning โ€บ how-to-add-all-numbers-in-range-to-set-python
Mastering Ranges in Python for Machine Learning
Create an empty set to store the numbers. Use a list comprehension to generate the sequence of numbers within the specified range. Convert the list to a set using the set() function.
๐ŸŒ
Medium
medium.com โ€บ @sjalexandre โ€บ python-tutorial-unit-14-a2f5bd0564fd
Python Tutorial โ€” Ranges, Sets, Tuples | Medium
August 12, 2023 - This code will output the numbers from 0 to 9. The range function generates a sequence of numbers starting from 0 by default, and stops before a specified number. A set in Python is an unordered collection of items that is iterable, mutable, and has no duplicate elements. Pythonโ€™s set class represents the mathematical notion of a set.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ built-in โ€บ set
Python set()
iterable (optional) - a sequence (string, tuple, etc.) or collection (set, dictionary, etc.) or an iterator object to be converted into a set. set() returns: an empty set if no parameters are passed ยท a set constructed from the given iterable parameter ยท # empty set print(set()) # from string ยท print(set('Python')) # from tuple print(set(('a', 'e', 'i', 'o', 'u'))) # from list print(set(['a', 'e', 'i', 'o', 'u'])) # from range ยท
Top answer
1 of 12
65

Using itertools.groupby() produces a concise but tricky implementation:

import itertools

def ranges(i):
    for a, b in itertools.groupby(enumerate(i), lambda pair: pair[1] - pair[0]):
        b = list(b)
        yield b[0][1], b[-1][1]

print(list(ranges([0, 1, 2, 3, 4, 7, 8, 9, 11])))

Output:

[(0, 4), (7, 9), (11, 11)]
2 of 12
16

You can use a list comprehension with a generator expression and a combination of enumerate() and itertools.groupby():

>>> import itertools
>>> l = [0, 1, 2, 3, 4, 7, 8, 9, 11]
>>> [[t[0][1], t[-1][1]] for t in
... (tuple(g[1]) for g in itertools.groupby(enumerate(l), lambda (i, x): i - x))]
[[0, 4], [7, 9], [11, 11]]

First, enumerate() will build tuples from the list items and their respective index:

>>> [t for t in enumerate(l)]
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 7), (6, 8), (7, 9), (8, 11)]

Then groupby() will group those tuples using the difference between their index and their value (which will be equal for consecutive values):

>>> [tuple(g[1]) for g in itertools.groupby(enumerate(l), lambda (i, x): i - x)]
[((0, 0), (1, 1), (2, 2), (3, 3), (4, 4)), ((5, 7), (6, 8), (7, 9)), ((8, 11),)]

From there, we only need to build lists from the values of the first and last tuples of each group (which will be the same if the group only contains one item).

You can also use [(t[0][1], t[-1][1]) ...] to build a list of range tuples instead of nested lists, or even ((t[0][1], t[-1][1]) ...) to turn the whole expression into a iterable generator that will lazily build the range tuples on the fly.

๐ŸŒ
Readthedocs
python-ranges.readthedocs.io โ€บ en โ€บ latest โ€บ set.html
The set โ€” python-ranges documentation - Read the Docs
A RangeSet can be constructed from any number of Range-like objects or iterables containing Range-like objects, all given as positional arguments. Any iterables will be flattened by one later before having their contents added to this RangeSet.
Find elsewhere
๐ŸŒ
Software Testing Help
softwaretestinghelp.com โ€บ home โ€บ python โ€บ python range function โ€“ how to use python range()
Python Range function - How to Use Python Range()
April 1, 2025 - As we mentioned earlier in this tutorial, the range() function returns an object (of type range) that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. Hence, running the range() function on its own will return a range object which is iterable. This object can easily be converted into various data structures like List, Tuple, and Set as shown below.
๐ŸŒ
Kite
kite.com โ€บ python โ€บ answers โ€บ how-to-convert-a-range-to-a-list-in-python
Kite is saying farewell - Code Faster with Kite
November 20, 2022 - The largest issue is that state-of-the-art models donโ€™t understand the structure of code, such as non-local context. We made some progress towards better models for code, but the problem is very engineering intensive.
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-convert-range-into-a-list
Convert Range into a List
In the following example, we take a range object starting at 4, and progressing upto 10 (excluding 10), and convert this range object into a list. # Take a range myrange = range(4, 10) # Convert range object into a list mylist = list(myrange) print(mylist) ... In the following example, we take ...
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ python range() explained with examples
Python range() Function Explained with Examples
March 17, 2022 - When you pass only one argument to the range(), it will generate a sequence of integers starting from 0 to stop -1. # Print first 10 numbers # stop = 10 for i in range(10): print(i, end=' ') # Output 0 1 2 3 4 5 6 7 8 9Code language: Python (python) Run ... Here, start = 0 and step = 1 as a default value. If you set the stop as a 0 or some negative value, then the range will return an empty sequence.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ python-program-to-find-numbers-in-range-and-not-in-set
Python Program to Find Numbers in Range and not in Set
March 27, 2026 - Set subtraction is the most efficient approach for finding numbers in range but not in set. Use the for loop method for simple cases or when you need to understand each step clearly.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_range.asp
Python range
Ranges are often used in for loops to iterate over a sequence of numbers. ... The range object is a data type that represents an immutable sequence of numbers, and it is not directly displayable. Therefore, ranges are often converted to lists for display.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Library for sets of integer ranges - Python Help - Discussions on Python.org
May 15, 2021 - Iโ€™m trying to remember a library Iโ€™d seen some time back. I didnโ€™t have a use for it then, but I do now. And of course I now canโ€™t remember what it was called ๐Ÿ™ Basically, I want to manage sets of integer ranges (the classic use case was sets of read articles in NNTP newsreaders).
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-range.html
Python range() Function
The most common form is range(n), given integer n returns a numeric series starting with 0 and extending up to but not including n, e.g. range(6) returns 0, 1, 2, 3, 4, 5. With Python's zero-based indexing, the contents of a string length 6, are at index numbers 0..5, so range(6) will produce exactly the index numbers for a string length 6, like this:
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ range-to-a-list-in-python
range() to a list in Python - GeeksforGeeks
July 11, 2025 - The simplest and most efficient way to convert a range object into a list is by using the list() constructor. ... This method is fast, concise, and highly readable. List comprehension provides another efficient and Pythonic way to convert a ...
Top answer
1 of 2
1

Here's the implementation I've come up with so far. A Range object represents an arbitrary openClosed range, and is hash-able, contain-able, and iter-able, but is neither a sequence nor a set. The DateRange subclass represents ranges of dates, which primarily simply requires defining the increment argument as timedelta(days=1) rather than simply 1.

class Range:  
  '''
  Represents a range, in the spirit of Guava's Range class.
  Endpoints can be absent, and (presently) all ranges are openClosed.
  There's little reason to use this class directly, as the range()
  builtin provides this behavior for integers.
  '''
  def __init__(self, start, end, increment=1):
    if start and end and end < start:
      raise ValueError("End date cannot be before start date, %s:%s" % (start,end))
    self.start = start
    self.end = end
    self.increment = increment

  def __repr__(self):
    return '[%s\u2025%s)' % (
      self.start or '-\u221E',
      self.end   or '+\u221E'
    )

  def __eq__(self, other):
    return self.start == other.start and self.end == other.end

  def __hash__(self):
    return 31*hash(self.start) + hash(self.end)

  def __iter__(self):
    cur = self.start
    while cur < self.end:
      yield cur
      cur = cur + self.increment

  def __contains__(self, elem):
    ret = True
    if self.start:
      ret = ret and self.start <= elem
    if self.end:
      ret = ret and elem < self.end
    return ret

class DateRange(Range):
  '''A range of dates'''
  one_day = timedelta(days=1)

  @staticmethod
  def parse(daterange):
    '''Parses a string into a DateRange, useful for
    parsing command line arguments and similar user input.
    *Not* the inverse of str(range).'''
    start, colon, end = daterange.partition(':')
    if colon:
      start = strToDate(start) if start else None
      end = strToDate(end) if end else None
    else:
      start = strToDate(start)
      end = start + DateRange.one_day
    return DateRange(start, end)

  def __init__(self, start, end):
    Range.__init__(self, start, end, DateRange.one_day)

def strToDate(date_str):
  '''Parses an ISO date string, such as 2014-2-20'''
  return datetime.datetime.strptime(date_str, '%Y-%m-%d').date()

Some usage examples:

>>> DateRange(datetime.date(2014,2,20), None)
[2014-02-20โ€ฅ+โˆž)
>>> DateRange(datetime.date(2014,1,1), datetime.date(2014,4,1))
[2014-01-01โ€ฅ2014-04-01)
>>> DateRange.parse(':2014-2-20')
[-โˆžโ€ฅ2014-02-20)
>>> DateRange.parse('2014-2-20:2014-3-22')
[2014-02-20โ€ฅ2014-03-22)
>>> daterange = DateRange.parse('2014-2-20:2014-3-2')
>>> daterange
[2014-02-20โ€ฅ2014-03-02)
>>> datetime.date(2014,1,25) in daterange
False
>>> datetime.date(2014,2,20) in daterange
True
>>> list(daterange)
[datetime.date(2014, 2, 20), datetime.date(2014, 2, 21), datetime.date(2014, 2, 22),
 datetime.date(2014, 2, 23), datetime.date(2014, 2, 24), datetime.date(2014, 2, 25),
 datetime.date(2014, 2, 26), datetime.date(2014, 2, 27), datetime.date(2014, 2, 28),
 datetime.date(2014, 3, 1)]
2 of 2
1

Is pd.Interval what you are looking for?

Quick demonstration with numbers and datetimes:

import pandas as pd
import numpy as np

interval_0_1 = pd.Interval(left=0, right=1, closed='right')
print(interval_0_1)

vals = np.linspace(-.5,1.5,5)
pd.DataFrame({'value':vals, 'in interval ' + str(interval_0_1):[val in interval_0_1 for val in vals]})

interval_2000 = pd.Interval(left=pd.to_datetime('01-01-2000'), right=pd.to_datetime('01-01-2001'), closed='left')
print(interval_2000)

vals = pd.date_range(start=pd.to_datetime('01-01-2000'), end=pd.to_datetime('01-01-2001'), periods=3)
pd.DataFrame({'value':vals, 'in interval ' + str(interval_2000):[val in interval_2000 for val in vals]})