TITLE: Prove if $f$ has a right inverse function: $f\circ g=id_x$ $\iff$ $f$ is onto $Y$
QUESTION [5 upvotes]: We have the sets $X,Y$ and $f:X\to Y, \ g: Y\to X $
Prove if $f$ has a right inverse function: $f\circ g=id_Y$ $\iff$ $f$ is onto $Y$ (surjective).

$\Leftarrow \forall y\in Y : \exists x\in X$ then $f(y)=x$ I need to show that $f\circ g(x)=x$ but I don't know how.
I have no clue on to start in the other direction. 
BTW, I found below similar question but they're either not quite the same as this one or I didn't understand the answers: 
Left inverse iff injective; right inverse iff surjective

REPLY [12 votes]: For $\boxed{\Leftarrow}$: assume $f$ is surjective. Then, for all $y\in Y$ there exists $x_y\in X$ such that $f(x_y)=y$. Define $g\colon Y\to X$ to be the function which maps each $y\in Y$ to such $x\in X$ (if there is more than one $x$, then the function $g$ maps $y$ to one of them chosen in an arbitrary way. This excludes the possibility that $g$ map $y$ to two distinct values, in which case it wouldn't be a function). It follows that
$$
\forall y\in Y,\quad f\circ g(y) = f( g(y) ) = f(y_x) = y
$$
and $f\circ g=id_Y$.
For $\boxed{\Rightarrow}$: assume $f\colon X\to Y,g\colon Y\to X$ are such that $f\circ g=id_Y$. Then for each $y\in Y$, $x_y\stackrel{\rm def}{=} g(y)\in X$ is a preimage of $y$ by $f$, as $f(x_y)=f\circ g(y) = id_Y(y)=y$. Hence $f$ is surjective.

REPLY [5 votes]: $\Leftarrow)$ For all $y\in Y$ there's $x\in X$ such that $f(x)=y$ so define $g$ by
$$g\colon Y\rightarrow X,\quad y\mapsto x$$
and we have
$$f\circ g=id_Y$$
$\Rightarrow)$ Let $y\in Y$ so $f\circ g(y)=id_Y(y)=y$ so let $x=g(y)\in X$ hence we have
$$\exists x=g(y)\in X,\quad f(x)=y$$
so $f$ is onto.