Hassan Sheikh Mohamud, Somalia’s former leader, has been elected president in a final vote open only to the country’s MPs.
He defeated the current president, Mohamed Abudallahi Farmajo, in 2017.
Due to security concerns about holding a larger election, the ballot was limited to Somalia’s 328 MPs, and one of them did not vote.
Mr Mohamud received 214 votes, outnumbering Mr Farmajo, who received 110 votes.
Three MPs are said to have tampered with their ballots.
The unusual circumstances highlight Somalia’s security challenges as well as the country’s lack of democratic accountability.
The outcome represents a comeback for Hassan Sheikh Mohamud, who served as Somalia’s president from 2012 to 2017, before being defeated by Mr Farmajo.
The elections, which were hotly contested and required a third round, were postponed for nearly 15 months due to infighting and security concerns.
Mr Mohamud was sworn in shortly after the final results were announced, prompting cheers and gunfire in the capital. He will be in office for the next four years.
Hundreds of parliamentarians cast ballots on Sunday at a fortified aircraft hangar in Mogadishu’s capital.
Explosions could be heard nearby as voting took place, but no casualties were reported, according to police.
Mr Mohamud, as the incoming president, will have to deal with the consequences of an ongoing drought, which the UN says puts 3.5 million Somalis at risk of severe famine.
But the most difficult task he faces is wresting control of much of Somalia from al-Shabab. The al-Qaeda-linked Islamist militant group still controls large parts of the country and conducts frequent attacks in Mogadishu and elsewhere.
The country is also being impacted by food and fuel inflation caused by the Ukraine conflict.
The African Union, with 18,000 troops, and the United Nations are assisting the government in its fight against al-Shabab.
One of the reasons Somalia has been unable to hold direct elections is the country’s insecurity. Since 1969, Somalia has not held a democratic election based on one person, one vote.
Following the election, there was a coup, dictatorship, and conflict involving clan militias and Islamist extremists.
This is only the third time that an indirect election for president has been held in Somalia. Previous ones were held in neighbouring Kenya and Djibouti.