A candidate dropped by the SNP a fortnight before the election has taken a Fife seat from Labour’s deputy Scottish leader.
Neale Hanvey was suspended by his party over allegations of anti-Semitism in comments he made on social media two years ago.
However, he still won the Kirkcaldy and Cowdenbeath constituency with a majority of 1,243 over Labour’s Lesley Laird.
Mr Hanvey took 16,568 votes, narrowly beating Mrs Laird’s 15,325.
First Minister Nicola Sturgeon had warned party members against campaigning for Mr Hanvey in the run up to the general election.
An emotional Mr Hanvey said it was an “amazing” victory and he was “very grateful” for the backing of his supporters and the electorate.
He said: “To turn it around in 12 days, I have an amazing team of people who believe in me and they know me.
“They know I do a good job and I certainly hope to prove them right and I will work my socks off.
He said: “I have never been over-confident. I haven’t taken anything for granted, I have fought for every vote before this issue arose and since then.
“I think my honesty and sincerity probably won a lot of people over.”
He said the result was “quite extraordinary”.
“From basically being cast aside 12 days ago to winning, it’s amazing.
“It’s a demonstration of trust from the people and I need to repay that.”
Mrs Laird said: “I am disappointed. I tried during the last two and a half years I have been MP to be community focused and a campaigning MP for the constituency but tonight result showed that it wasn’t to be and that’s democracy.”
She said she believed her team had run a very positive campaign but added: “Clearly voters have made their choice and that, as a politician, is ultimately what happened.”
Mr Hanvey appeared on the ballot as an SNP candidate, even though he was standing as an independent, because it was too late to change the paper.
He has maintained he hopes to return to the party after a review has been carried out.
Voter turnout in Kirkcaldy and Cowdenbeath was 64.69%, up on the 63.6% of 2017.
Conservative candidate Kathleen Leslie won 9,449 votes, Liberal Democrat Gill Cole-Hamilton 2,903, Scottish Green Scott Rutherford 1,628 and Mitch William, for the Brexit Party, 1,132.