Mr. Essebsi told French television France 24 that even though the official results were not completed, he had accepted Mr. Ghannouchi’s congratulations with appreciation. His party announced its victory on its Facebook page. “We won,” it said. “Long live Tunisia.”

The swing away from Ennahda, a large, well-organized party built along the lines of the Muslim Brotherhood with deep roots throughout the country, to Nidaa Tounes surprised many. Nidaa Tounes is a newly formed alliance of former government officials, left-wing politicians and secularists, who came together in 2012 in opposition to the Islamists. The party had appeared unorganized and divided internally, while Ennahda was known to have a committed and disciplined core of supporters.

Ennahda had won 89 seats in 2011, making it the largest party in Parliament after the revolution that overthrew the government of President Zine el-Abidine Ben Ali. Many Tunisians at the time said they had voted for Ennahda members because of their religious profile, hoping that they would be honest and not corrupt like the Ben Ali entourage.

Many Ennahda members had emerged from prison or had returned from exile after the revolution and were afforded some sympathy. Yet they proved largely inexperienced and unable to manage the mounting instability, and alienated many by allowing a rapid spread of Islamist groups, some of which turned to violence.

While Tunisians are overwhelmingly Muslim, and their sympathies lie with their fellow Arabs — in particular for those suffering in conflict, whether Palestinians, Syrians or Libyans — they have sharply rejected insurgent violence at home and support the Tunisian Army and the police as they battle Islamist insurgents active inside Tunisia. Still, some 3,000 young Tunisians have joined the extremist group that calls itself the Islamic State to take up arms in Syria and Iraq, a disproportionally high number for such a small country.