When I saw this online, I had to try it for myself.

Looking around online, I've seen several explanations for this including static electricity (like what makes a rubbed balloon stick to a wall or your head).

But, based on what you have to do to make it work, my guess is that it's paint on the pencil gripping the coarseness of the paint on the wall.  Just a guess!

Give it a try, but keep in mind it may leave a mark on your walls.