A class and utilities for encoding variable objects.

The Variables class is intended to be used as an attribute of other classes, such as DiscreteQuadraticModel and SampleSet.

The requirements for the class are:
  • Have a minimal memory footprint when the variables are labeled [0, n)

  • Behave like a list for iteration and getting items

  • Behave like a set for determining if it contains an item

  • Constant time for finding the index of an item

Variables Class#

class Variables[source]#

Set-like and list-like variables tracking.


iterable (iterable[Variable], optional) – An iterable of labels. Duplicate labels are ignored. All labels must be hashable.


The Variables object encodes an ordered set of variables.

>>> variables = dimod.variables.Variables(['a', 'b', 0, 1])
>>> print(variables)
Variables(['a', 'b', 0, 1])

Variables is a sequence.

>>> variables[0]  # O(1) element access using integer indices
>>> len(variables)  # defines a length

Unlike most other sequence types, Variables provides O(1) lookup for the index of an element.

>>> 0 in variables  # O(1) lookup
>>> variables.index('b')  # O(1) lookup

Therefore Variables is also a set.

>>> variables & [0, 'a', 'f']
Variables([0, 'a'])

Variables inherits from Sequence and Set so it inherits all of the provided mixin methods.

>>> list(reversed(variables))
[1, 0, 'b', 'a']
>>> variables.count('b')
>>> variables.count('hello')



Return True if the variables are labeled [0,n).


index(v[, permissive])

Return the index of v.


Return the number of times v appears in the variables.


Return an object that is JSON-serializable.

Mutation Methods#


The Variables class comes with a number of semi-public methods that allow other classes to manipulate its contents. These are intended to be used by parent classes, not by the user. Modifying a Variables object that is an attribute of a class results in undefined behaviour.

_append([v, permissive])

Append a new variable.


Remove all variables.

_extend(iterable[, permissive])

Add new variables.


Remove the last variable.


Relabel the variables in-place.


Relabel the variables as integers in-place.


Remove the given variable.