I recently got bitten by a couple bugs in a project I was doing in Python and thought I’d share. Short and sweet, I’ll get directly to the point.
sorted() method in Python does not sort an iterable in place. It returns the sorted iterable. Remember to catch the sorted iterable into a new variable.
my_list = [5, 3, 1, 4]
sorted(my_list, reverse = True) # Useless, unless you are printing it directly
my_list = sorted(my_list, reverse = True) # Correct
The next one is a bit more subtle. The
extend() method to a
list is useful if you want to add the contents of a
list _individually_ to another
list. But if you are adding a
string to a
extend() method will split the
string, treating it as a
list of characters. The following example will make it clear.
my_str = 'randomness'
my_list = 
my_list.extend(my_str) # my_list = ['r', 'a', 'n', 'd', 'o', 'm', 'n', 'e', 's', 's']
my_list.extend(['hello', 'world']) # my_list = ['r', 'a', 'n', 'd', 'o', 'm', 'n', 'e', 's', 's', 'hello', 'world']
Small things. Must remember. So long, and happy Pythoning!