I’m in Toronto on a student visa and I am planning to go to the UK to visit my friend who is there on on student visa too. I have applied for a short stay UK Visa. I wanted to ask: can I fly home to South Africa from the UK during the period of my short stay visa OR must I first fly back to Toronto then I take a flight to South Africa?
You don't need to go back to Canada. The UK only cares that you leave the UK at the end of your visit: as long as you leave, they don't care where you go. In the same way, South Africa doesn't care where you arrive from, and Canada doesn't care where you go while you're outside Canada. (They might have rules against going to specific countries, such as North Korea, but that kind of issue doesn't apply, here.)
People often mistakenly say that you need a return ticket (which would mean going back to Canada). You don't: you just need an onward ticket, i.e., a ticket to leave the UK. (Officially speaking, for the UK, you don't even need an onward ticket but, if an immigration officer suspects you might stay longer than you're supposed to, not having a ticket out of hte UK will be taken as more evidence of that.) The same is true with almost all countries – as long as you leave, they don't care where you leave to.
As a rule a country's immigration service does not know, and certainly does not care, where you have come from.
As long as you have the right permission to enter, UK immigration does not care if you have come from Canada or South Africa. Canada does not care if you come from South Africa or UK, and assuming you are a citizen or legal resident of South Africa they absolutely definitely do not care where you arrive from.
There are some very rare exceptions in the cases of countries it is illegal for certain nationals to visit, but they do not apply to you.