We create a random graph with $n$ vertices in such a way that for each pair of vertices $\{i, j\}$, we connect them with an edge with probability $p$ (each time drawing independently). Let $X$ be the number of pairs of vertices $\{u, v\}$ such that the distance from $u$ to $v$ is greater than 2. For example, for the graph $G=(V, E), V=\{1,2,3,4,5\}, E=\{\{1,2\},\{2,3\},\{3,4\}\}$, we have $X=5$ (the pair $\{1,4\}$ and four pairs $\{i, 5\}$ for $i<5$).
a) Calculate $\mathbb{E}[X]$.
b) Calculate Var $X$.
I think that $$\mathbb{E}[X] = \binom{n}{2} - \mathbb{E}[Y_1] - \mathbb{E}[Y_2]$$
where $Y_1 =$ the number of pairs of vertices separated by a distance of $1$,
and $Y_2 =$ the number of pairs of vertices separated by a distance of $2$.
Then $$\mathbb{E}[Y_1] = \binom{n}{2} \cdot p$$
because each pair is connected with probability $p$, and
$$\mathbb{E}[Y_2] = \binom{n}{2} (1-p) (n-2) p^2$$
because each pair of vertices is not directly connected with probability $(1-p)$, and has $(n-2)$ vertices through which it can be indirectly connected with probability $p^2$ each.
However, for $n = 10$ and $p = \frac{1}{2}$, it turns out that $\mathbb{E}[Y_2] = \binom{10}{2}$, which is the number of all possible pairs, so I suspect that the same events are counted multiple times.
How can I find $\mathbb{E}[Y_2]$, and why is what I have now wrong (why can't we consider each pair of vertices independently thanks to linearity of expectation)?
Your setup is generally good, and you’re right that you can consider each pair separately due to linearity of expectation.
But your expression for $\mathsf E\left[Y_2\right]$ is wrong. The $n-2$ events that the two vertices are connected via another vertex are independent, so the probability for none of them to occur is $\left(1-p^2\right)^{n-2}$, and thus
$$ \mathsf E\left[Y_2\right] = \binom n2(1-p)\left(1-\left(1-p^2\right)^{n-2}\right) \;. $$
For $n=10$ and $p=\frac12$, this is
\begin{eqnarray*} \mathsf E\left[Y_2\right] &=& \binom{10}2\left(1-\frac12\right)\left(1-\left(1-\left(\frac12\right)^2\right)^{10-2}\right) \\ &=& \frac{45}2\cdot\left(1-\left(\frac34\right)^8\right) \\ &=& \frac{2653875}{131072} \\[4pt] &\approx&20.25 \;. \end{eqnarray*}