Somalia’s former leader Hassan Sheikh Mohamud has been elected president after a final vote that was only open to the country’s MPs.
He defeated the current president, Mohamed Abudallahi Farmajo, who has been in office since 2017.
The ballot was limited to Somalia’s 328 MPs due to security concerns over holding a wider election, and one of them did not cast a vote.
Mr Mohamud received 214 votes, defeating Mr Farmajo who won 110 votes.
Three MPs are reported to have spoiled their ballots.
The unusual circumstances highlight Somalia’s security issues as well as the lack of democratic accountability.
The result marks a comeback for Hassan Sheikh Mohamud, who served as Somalia’s president between 2012 and 2017 before he was defeated by Mr Farmajo.
The elections – which were hotly contested and went to a third round – were delayed for almost 15 months due to infighting and security issues.
Mr Mohamud was sworn in shortly after the final results were announced, prompting supporters in the capital to cheer and fire guns into the air. He will serve for the next four years.
In the vote on Sunday, hundreds of parliamentarians cast their ballots at a fortified aircraft hangar in the capital Mogadishu.
Explosions could be heard nearby as voting was taking place, but police said no casualties were reported.
As the incoming president, Mr Mohamud will have to deal with the impact of an ongoing drought in which the UN says 3.5 million Somalis are at risk of severe famine.
But the big task he faces is to wrest control of much of Somalia from al-Shabab. The al-Qaeda-linked Islamist militant group continues to dominate large parts of the country and carries out frequent attacks in Mogadishu and elsewhere.
The country is also being affected by food and fuel inflation sparked by the war in Ukraine.
The government is backed in its fight against al-Shabab by the African Union, in the shape of some 18,000 troops and the United Nations.
The instability is one of the reasons why Somalia has been unable to hold direct elections. Somalia has not had a one-person-one-vote democratic election since 1969.
That vote was followed by a coup, dictatorship and conflict involving clan militias and Islamist extremists.
This is only the third time that the indirect election for president has been able to take place in Somalia itself. Previous ones were held in neighbouring Kenya and Djibouti.