STOCKHOLM — Prime Minister Stefan Lofven of Sweden lost a vote of confidence on Tuesday after an election this month led to the ouster of his minority coalition and left the country with a hung Parliament, with both main political blocs refusing to cooperate with the anti-immigrant Sweden Democrats.

Mr. Lofven, the leader of the Social Democratic Party who has been prime minister for four years, will continue in a caretaker role until the formation of a new government that has the command of Parliament.

Lawmakers voted 204 to 142 against Mr. Lofven, while three abstained, after the election on Sept. 9 in which neither the left-leaning bloc led by the Social Democrats nor the Moderates-led center-right opposition managed to secure a majority. The no-confidence vote was mandatory.

Mr. Lofven says he is still optimistic that he can form a government, but with neither bloc holding a majority and neither willing to work with the Sweden Democrats, the vote means Sweden faces weeks of political uncertainty.