Python
is full of surprises!
It's one of those languages with a strong personality that always finds a way to stand up.
Here are 10 interesting —and probably surprising— Python features.


It's one of those languages with a strong personality that always finds a way to stand up.
Here are 10 interesting —and probably surprising— Python features.



This comes in handy whenever you are trying to track down why your program is eating all your available RAM.
I'm constantly dealing with multi-dimensional arrays that eat a lot of memory, so sys.getsizeof() is



Swapping the value of two variables is one of those things that you learn in the second week of your programming career.
And it's always the same: use a temporal variable to make the swap.
Not with Python.


Using Python's enumerate built-in function you can loop over a list of elements and get an automatic counter without needing an extra variable.
This makes your code so much cleaner. Plus you don't have to remember to increment it!


This is one of those things that I've only seen in Python.
You can add an "else" clause to a for loop, and it will execute after the loop completes normally.
If the loop finds a "break" statement, the "else" clause will not execute.


Using the built-in function dir() you can return a list of the attributes and methods of any object.
Very useful when you are trying to figure out how to do something and need to know whether the object supports it.


You can chain conditional operators in Python to make expressions look more natural.
This is one of my favorites!
(When evaluating them, keep in mind that all comparison operations have the same priority.)


You can return more than one value from a function without needing to create a separate structure to store those values.
I've always hated to do that, so this is a great feature that I use all the time!


This one is also great to keep your code compact and clean. You can assign the same value to a bunch of variables at the same time.
Keep in mind that you are basically referencing the same object, not creating copies of it.


Whenever you have multiple sequences and you want to loop through them in parallel, you can use zip() to aggregate them together.
Once you get the hang out of this one, you'll use it all the time.


This one took me a while to find out, but it's a good one!
Whenever you need a multi-line string, you don't have to fill out your code with weird operators after each line. Instead, you can use triple-quotes.

Were you using all of these already?
Which one was more surprising to you?
Which one was more surprising to you?