MADRID — Two days after elections weakened his hand, Pedro Sánchez, Spain’s caretaker Socialist prime minister, made an abrupt U-turn on Tuesday and agreed to partner with a hard-left party he had previously rejected to form a government.

The preliminary deal between the Socialists and the smaller party, Unidas Podemos, came after five months of fruitless talks between them. Their partnership requires the support of several smaller parties in Parliament and still would leave Spain with a minority coalition government.

But the step was a breakthrough for a country where national parties, left and right, have been reluctant to compromise and come together, and it had the potential to break Spain’s long political deadlock.

It would also make Spain a standout in Europe, as one of the few countries with a left-wing government.