diff --git a/qiskit/aqua/operators/list_ops/list_op.py b/qiskit/aqua/operators/list_ops/list_op.py index f6ba958c8a..32e3fcd9d4 100644 --- a/qiskit/aqua/operators/list_ops/list_op.py +++ b/qiskit/aqua/operators/list_ops/list_op.py @@ -129,7 +129,10 @@ def primitive_strings(self) -> Set[str]: @property def num_qubits(self) -> int: - return self.oplist[0].num_qubits + num_qubits0 = self.oplist[0].num_qubits + if not all(num_qubits0 == op.num_qubits for op in self.oplist): + raise ValueError('Operators in ListOp have differing numbers of qubits.') + return num_qubits0 def add(self, other: OperatorBase) -> OperatorBase: if self == other: diff --git a/releasenotes/notes/listop-check-num-qubits-ce3a02fcc862771a.yaml b/releasenotes/notes/listop-check-num-qubits-ce3a02fcc862771a.yaml new file mode 100644 index 0000000000..a7c60ec807 --- /dev/null +++ b/releasenotes/notes/listop-check-num-qubits-ce3a02fcc862771a.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + Make ListOp.num_qubits check that all ops in list have the same num_qubits + Previously, the number of qubits in the first operator in the ListOp + was returned. With this change, an additional check is made that all + other operators also have the same number of qubits. diff --git a/test/aqua/operators/test_op_construction.py b/test/aqua/operators/test_op_construction.py index 7bb29bb454..6b7a10b62d 100644 --- a/test/aqua/operators/test_op_construction.py +++ b/test/aqua/operators/test_op_construction.py @@ -508,6 +508,24 @@ def test_list_op_parameters(self): self.assertEqual(list_op.parameters, set(params)) +class TestOpMethods(QiskitAquaTestCase): + """Basic method tests.""" + + def test_listop_num_qubits(self): + """Test that ListOp.num_qubits checks that all operators have the same number of qubits.""" + op = ListOp([X ^ Y, Y ^ Z]) + with self.subTest('All operators have the same numbers of qubits'): + self.assertEqual(op.num_qubits, 2) + + op = ListOp([X ^ Y, Y]) + with self.subTest('Operators have different numbers of qubits'): + with self.assertRaises(ValueError): + op.num_qubits # pylint: disable=pointless-statement + + with self.assertRaises(ValueError): + X @ op # pylint: disable=pointless-statement + + class TestListOpComboFn(QiskitAquaTestCase): """Test combo fn is propagated."""