Question: In a Parliamentary democracy, general elections appoint constituency representatives. Most such appointees are members of parties with internally determined leaders. One or more parties then form a government, with one of these party leaders the head of government.

However, it's theoretically possible that a party that enters or stays in government due to its electoral performance has to change leader, due to that individual losing their seat. (Party leaders typically come from safe seats to prevent this.)

Has this ever actually happened? I'd be interested if this happened in the UK, or failing that in any nation with a Westminster system.

Answer: 
That's incredibly rare as you mentioned, but it has happened before twice in Canada to the same Prime Minister though he remained Prime Minister.

Prime Minister William Lyon Mackenzie King lost his seat [in York North in 1925](https://en.wikipedia.org/wiki/Canadian_federal_election,_1925) and his seat [in Prince Albert in 1945](https://en.wikipedia.org/wiki/Canadian_federal_election,_1945) but went on to be Prime Minister on both occasions. However, his party lost their majority in Parliament on both occasions, though they won the by-election in 1925 and was the largest party in 1945.

---

Usually, leaders would only lose their seat if their party loses too, in which has occurred twice in Australia and once in the UK.

John Howard lost his seat, Bennelong, in the [2007 Australian federal election](https://en.wikipedia.org/wiki/Australian_federal_election,_2007) while Stanley Bruce lost his seat, Flinders, in the [1929 Australian federal election](https://en.wikipedia.org/wiki/Australian_federal_election,_1929).

In the UK, Arthur Balfour lost his seat in Manchester East after the [Conservative landslide defeat in 1906](https://en.wikipedia.org/wiki/United_Kingdom_general_election,_1906).

These examples are [referenced from The Guardian](https://www.theguardian.com/notesandqueries/query/0,,-199840,00.html).
Something like *nearly* happened in North-Rhine-Westphalia in Germany [recently](https://en.wikipedia.org/wiki/North_Rhine-Westphalia_state_election,_2017), where the candidate for prime minister of the winning party, Armin Laschet, won his seat by only a slim margin ([article in German](https://www.merkur.de/politik/nrw-wahl-2017-cdu-spitzenkandidat-laschet-gewinnt-direktmandat-zr-8308380.html)).

If he had lost it, the party would have had to do some shenanigans to get him into parliament (e.g. some other winning candidate would have had to renounce his seat) since he must be a member of parliament to become prime minister.