# How the single qubit unitary (U) calculates when apply a gate to only one qubit at a time?

Qiskit Textbook, Chapter 2, Section 2.2. Single Qubit Gates on Multi-Qubit Statevectors (here).

In here, they have described that: If we want to apply a gate to only one qubit at a time (such as in the circuit below), we describe this using tensor product with the identity matrix, e.g.: $$X\otimes I$$.

By executing the given code, the tensor product matrix generated corresponds to when X-gate is applied to qubit 1 in circuit.

qc = QuantumCircuit(2)
qc.x(1)
qc.draw()
# Simulate the unitary
usim = Aer.get_backend('unitary_simulator')
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
# Display the results:
array_to_latex(unitary, pretext="\\text{Circuit = } ")


The output is:

When I tried to change the $$X$$ gate position to qubit 0 (qc.x(0)) then the tensor product matrix is changed (refer to image attached below). My doubt is: in this case how is the tensor product calculated, shouldn't it be the same?

Short answer, tensor product is not commutative. Therefore, in the general case, $$A \otimes B \not = B \otimes A$$. By calculating the matrices $$I \otimes X$$ and $$X \otimes I$$, you'll see the difference.
Applying $$X$$ to qubit 0 corresponds to the following matrix: $$I \otimes X = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \otimes \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} = \begin{pmatrix} 1 \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} & 0 \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \\ 0 \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} & 1 \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \end{pmatrix} = \begin{pmatrix} 0 & 1 & 0 & 0 \\ 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{pmatrix}$$
And applying $$X$$ to qubit 1 corresponds to:
$$X \otimes I = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \otimes \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} = \begin{pmatrix} 0 \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} & 1 \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \\ 1 \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} & 0 \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \end{pmatrix} = \begin{pmatrix} 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \\ 1 & 0 & 0 & 0 \\0 & 1 & 0 & 0 \end{pmatrix}$$
So, you write the matrices in the same order as the qubits. For example, if you have the register $$|c\rangle\otimes|b\rangle\otimes|a\rangle$$ and we apply the matrix $$C\otimes B\otimes A$$, $$A$$ will be applied to $$|a\rangle$$, $$B$$ to $$|b\rangle$$, and $$C$$ to $$|c\rangle$$. Furthermore, $$|a\rangle$$ would correspond to qubit 0, $$|b\rangle$$ to qubit 1, and $$|c\rangle$$ to qubit 2.