After serving as the main villain of two films, Loki has grown into the Thor franchise's reluctant hero who now sides with the good guys more than the bad guys. This version of Loki has less in common with his comic book comic counterpart and instead bears more striking similarities to the X-Men villain, Magneto.
In 2011's Thor, Loki secretly plotted to have his brother thrown out of Asgard so that he could carry out a hostile takeover of the kingdom. The Avengers saw Loki return as the villain, where he led an army of Chitauri against the planet Earth. In Thor: The Dark World, the two brothers had to work together to defeat Malekith and avenge their mother. After faking his death, Loki pretended to be Odin and stole the throne of Asgard. Loki's plans were immediately thwarted at the beginning of Thor: Ragnarok, and the bulk of the film showed him on the same side as Thor, Hulk, and Valkyrie. Loki pretended to side with Thanos in Avengers: Infinity War before being murdered by Thanos. His death became a major motivator for Thor going forward.
The way the Thor franchise handles Loki draws a lot of comparisons to the portrayal of Magneto in X-Men comics and movies. The powerful mutant who hates humanity doesn't share the X-Men's ideology, but is still willing to put their differences aside when necessary. In the span of a single movie or comic book, Magneto can go from a ruthless villain to a valuable - though not exactly trustworthy - ally.
Magneto typically starts out as an antagonist but is eventually convinced to side with the heroes to make a united stand against a common enemy. Magneto's reputation makes it possible for the character to take on a variety of roles. He can be an anti-hero, a hero, or a villain. Not only that, but he can change sides before the story is over.
At this point, this is what fans have come to expect from Loki as well. Loki went from villain to hero in Thor: The Dark World, Thor: Ragnarok and Avengers: Infinity War, though in this last case his deception was really just a farce. The Marvel Cinematic Universe currently doesn't have its own Master of Magnetism (yet) but right now it doesn't need one. Loki is filling that role just fine on his own. This kind of unpredictability will give Marvel plenty of leeway when it comes to his portrayal in the upcoming Loki TV series for Disney+.