Pellegrini touched the wall first at one minute, 54.73 seconds with American Ledecky, the reigning world and Olympic champion, and Australia’s Emma McKeon sharing silver as they both clocked 1:55.18.
The 28-year-old Pellegrini, who also won the world title over 200m at home in Rome in 2009 and Shanghai in 2011, said this was the last 200m freestyle of her career as she eyes retirement.
“It is an amazing medal. I thought I would get on the podium, but not the gold medal — I thought Ledecky would win it ,” said Pellegrini, who finished fourth in last year’s Olympic final in Rio de Janeiro.
“Before the last 50 metres, I thought I was in the same position as Rio, I didn’t know where I would get the energy. This is the last 200 freestyle of my career.”
Having become the first female swimmer to win 12 world titles with victory in the 1500m freestyle final on Tuesday, Ledecky had been the favourite in the 200m final, but lost on the wall.
This is the first time in 13 finals, spanning three world championships and four years, that Ledecky has not finished with a gold medal and she says the defeat will motivate her for years to come.
“I knew it was going to be a tough field, but I can’t complain with the silver,” said the 20-year-old Ledecky.
“I don’t know what it was, I’ll have to review the race video and see what I could have done better.
“That will light some fire under me for the next couple of years.”
McKeon went out hard, leading at the first turn with Ledecky only fifth after the first 50m.
Ledecky powered through the field and when she touched the wall second to McKeon at the final turn, it looked like the gold would go to one of the leading pair.
However, Pellegrini, the 2008 Beijing Olympic champion, put in a powerful final 50m to snatch the gold on the wall.
Home favourite Katinka Hosszu of Hungary, who had retained her 200m individual medley title on Monday, finished only seventh in a strong field.
Download our app and read this and other great stories on the move. Available for Android and iOS.