Confusion in proof for the Law of the Unconscious Statistician, discrete case Background
The Law of the Unconscious Statistician states that given the formula for $E[X] = \sum\limits_x xP(X=x)$, we can also determine the expectation for a function of $X$ as such:
$$E[g(x)] = \sum\limits_x g(x)P(X=x)$$
Question
On Wikipedia, there is a short proof for the discrete case.

But I fail to grasp what goes on between lines 2 and 3 in the calculation.
What I do understand

*

*$X,\ \  Y=g(X)$ are discrete random variables

*$x,\ \  y$ are values that $X, Y$ can take, respectively

*$f_X(X),\ \  f_Y(y)$ are probability mass functions, or more familiarly, $P(X=x),\ \  P(Y=y)$

*the goal of the proof is to represent $E[Y]$ in terms of $f_X(x)$ instead of $f_Y(y)$ as the former is known, and the latter is not

What I don't understand
The subscript under the second sum, $x \ : \ g(x)=y$ makes it so I don't understand what is being summed over.
Moreover, I don't understand how a factor inside a sum (from line 2) can be replaced with a second sum (in line 3).
Can this step of the proof be re-written in a way that is more clear?
 A: IMO a clearer proof expresses the subscript "$x:g(x)=y$" in indicator form. The indicator $I(A)$ of a statement equals $1$ if statement $A$ is true, and equals zero otherwise.
First apply the definition of expectation to write
$$E[g(X)] = \sum _y y P(g(X)=y)\tag1
$$
where the sum is taken over all possible values $y$ for $Y$. Next, compute $P(g(X)=y)$ as the sum of $P(X=x)$ for all $x$ such that $g(x)=y$.
This is written
$$P(g(X)=y)=\sum_x P(X=x)I(g(x)=y),\tag2$$
i.e., we are summing the product of $P(X=x)$ with $I(g(x)=y)$ as $x$ ranges over all possible values for $X$. Substitute (2) into (1), and interchange the summations:
$$\begin{aligned}E[g(X)]&=\sum_y y \left(\sum_x P(X=x) I(g(x)=y)\right) \\
&= \sum_x \sum_y yP(X=x)  I(g(x)=y)\\
&=\sum_x P(X=x)\left(\sum_y yI(g(x)=y)\right)\\
&\stackrel{(*)}=\sum_x P(X=x)g(x)
\end{aligned}\tag3$$
To argue (*), observe that the expression $\sum_y yI(g(x)=y)$ is summing over all possible values of $y$. But as $y$ varies, the only time the indicator  $I(g(x)=y)$ lights up is when $y=g(x)$.
