I want to prove the formula for the expected value of a discrete function. The proof in my book goes like this $$ \begin{split} \sum_k \left[ \sum_{g(j)=k} g(j) p_X (j) \right] &= \sum_k k \left[ \sum_{g(j)=k}p_X (j) \right] \\ & = \sum_k k \left[ \sum_{g(j)=k}P(X=j) \right] \\ & = \sum_k k P(g(X)=k) \\ & = \sum_k k p_Y(k) \\ & = \mathbb(E(Y)) \end{split} $$ . I don't understand why the first step of the second image is equal to E(y) in the theorem in the first image. Also why is this equal and $$ \sum_k k \left[ \sum_{g(j)=k}P(X=j) \right] = \sum_k k P(g(X)=k) $$ ?
Thanks in advance!