Why did Peter have a sword? Because Jesus had previously said, "Times are changing. Be prepared for hostility. Buy a sword" (see Luk 22:36). Perhaps Jesus spoke figuratively, but Peter must have taken Him literally.
It was Thomas who had said, to Jesus, "We'll die with You if necessary" (see Joh 11:16)but it's Peter, here, who was ready to do just that. While commendable, Peter's zeal was misdirected because it was not based on knowledge. Why didn't Peter understand what was happening? Why didn't he see clearly that everything was transpiring according to pattern? Because instead of praying, Peter had been sleeping (Mat 26:40). Consequently, Peter wakes up groggy, sees a battle, whips out his sword, and swings it wildly.
So, too, many times we as disciples hurt people unnecessarily as we whip out the Scriptures and let them fly, all the while thinking, Others may be carnal and weak, but not me, Lord. You can count on me. I'll stand up for You. Like Peter, we cause pain and hurt whenever our zeal is not based on the knowledge that can only come from spending time in prayer.
Luke tells us at this point, Jesus reached down, picked up Malchus' ear, and placed it back on his head (Luk 22:51). Had Jesus not done so, there would have been four crosses on Calvary a few hours later because Peter would have been crucified for such an offense. The last recorded miracle of our Lord was to heal a wound inflicted by one of His right hand men who was flailing the sword indiscriminately and inappropriately.