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).
While not Parliamentary, this is close enough. [Newt Gingrich](https://en.wikipedia.org/wiki/Newt_Gingrich), who was the US Speaker of the House, lost his position 1998 after his party lost only 5 seats. While that was not enough to cost them the majority (i.e. they still won overall), it was enough to spark a revolt within the party against a weak election showing they blamed him for. Gingrich, rather than lose an election for Speaker, resigned.

Also, [Eric Cantor](https://en.wikipedia.org/wiki/Eric_Cantor), House Majority Leader, neglected working hard in the primaries and wound up losing to a political newcomer, who then went on to win Cantor's seat in the 2014 Republican landslide.