A few Python ‘Gotchas’: sorted() and list.extend()

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.

The 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 list, the 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!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s