The deadlock was finally resolved when the Maoists, the largest single party, decided to withdraw their own candidate and to support Jhalanath Khanal, the chairman of a smaller allied party.
Nepal has been without a functioning government since June.
Many Nepalese are angry, saying issues including the economy and the peace process have been neglected.
“Jhalanath Khanal secured 368 of the 598 votes cast, giving him a majority,” speaker Subash Chandra Nemwang told parliament.
It was the 17th time Nepalese MPs had voted to elect a new prime minister. Changes in the election process helped to clear the deadlock.
Jhalanath Khanal’s victory came after a last-minute decision by the Maoist party to withdraw their own candidate – Pushpa Kamal Dahal, also known as Prachanda – from the race.
An hour before the vote was due, they announced they would support Mr Khanal, whose Communist Party of Nepal – Unified Marxist-Leninist (CPN-UML) is the third largest in the house.
Analysts say the Maoists made this decision because Mr Khanal was sympathetic to their views, and it was unlikely that they would have been able to gain enough support to lead a majority government themselves.