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: 
I’d like to point out the answer about Canada was wrong. Sitting Prime Ministers have lost their seats four times. The first time was in 1921 when Arthur Meighen lost his seat and the Conservatives, who had been in power since 1911, lost the election to William Lyon Mackenzie King. He had to run in another safe seat to sit in Parliament. Meighen then became the only sitting PM to lose his seat and the election a second time, in the 1926 election.

Meighen won the election of 1925, since he won the most seats, but could not form a government. King became PM when he formed a coalition with the Progressive party. Scandal forced him to resign, and a constitutional crisis was triggered when the Governor-General, Lord Byng, refused to allow a new election and invited Meighen to try to form a government. It lasted 88 days, and Meighen lost his seat in the next election and King and the Liberals formed the government again.

King lost his seat in the 1925 election, so he was the 2nd sitting PM to lose his seat, but still put together a coalition to form a government and was elected in a by-election in a safe seat after a resignation.

The 3rd time was Meighen’s loss in the 1926 election, and the fourth was King’s 1945 loss.
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.