Python Friday #24: Multiple Return Values?

In a talk at NDC I saw an interesting feature of Python: A method returned not one but two values, a list of parsed entries and a list of entries with errors. This powerful feature is called unpacking of a tuple and can make your code a lot simpler.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

Multiple return values?

A simple example of a method that returns two values can look like this one:

To assign the return value of the multiple() method to two variables, we just write them on the left side of the assignment:

 

How does it work?

Python does not really have multiple return values. What we create with a, b is the short form of a tuple. This tuple is returned and automatically unpacked when we assign it to multiple values. If we assign the return value to a single variable, we see that the it is of type tuple:

 

Why would you use this feature?

I see this feature as a great help when you work with data and only want to process it once, but it can have multiple categories of return values (like the valid entries and the ones with an error). If we have a list of numbers and need to know which ones are odd and which are even, we can write this function:

All we now need to do is to call this method with a list of numbers:

 

Conclusion

Tuple unpacking is a nice little feature that can increase the readability of your code. As with other features, use it when it makes sense and do not apply it to every problem.

3 thoughts on “Python Friday #24: Multiple Return Values?”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.