Pedro Sánchez was sworn in on Saturday as Spain’s new prime minister, capping a remarkable personal comeback and a week of political upheaval that culminated in the first removal of an incumbent leader by Parliament in modern Spanish history.

Little more than a year ago, Mr. Sánchez, 46, seemed lost in the political wilderness, deposed as the leader of the Socialist party after two record electoral defeats. And the man he has now replaced, Mariano Rajoy, 63, was seen as the great survivor of Spanish politics, one of Europe’s longest-serving heads of government.

But Mr. Sánchez was unexpectedly re-elected as Socialist leader seven months after his ousting. Then, when Mr. Rajoy’s conservative Popular Party was tarnished by corruption — a court last week found the party guilty of operating a slush fund — he pounced, assembling parliamentary backing for a vote of no confidence in Mr. Rajoy, which passed on Friday.

Still, his tenure could be short. The Socialist party holds just under a quarter of the seats in Parliament. Like the vote against Mr. Rajoy, his government will rely on support from the far-left Podemos party and nationalists from Catalonia and the Basque region.