Do you need to create a function that returns a tuple but you don’t know how? No worries, in sixty seconds, you’ll know! Go! ?
A Python function can return any object such as a tuple. To return a tuple, first create the tuple object within the function body, assign it to a variable
your_tuple, and return it to the caller of the function using the keyword operation “
For example, the following code creates a function
create_tuple() that adds all numbers 0, 1, 2, …, 9 to the tuple
your_tuple, and returns the tuple to the caller of the function:
def create_tuple(): ''' Function to return tuple ''' your_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9) return your_tuple numbers = create_tuple() print(numbers) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Note that you store the resulting tuple in the variable
numbers. The local variable
your_tuple that you created within the function body is only visible within the function but not outside of it. So, if you try to access the name
your_tuple, Python will raise a
>>> print(your_tuple) Traceback (most recent call last): File "C:UsersxcentDesktopcode.py", line 9, in <module> print(your_set) NameError: name 'your_tuple' is not defined
To fix this, simply assign the return value of the function — a tuple — to a new variable and access the content of this new variable:
>>> numbers = create_tuple() >>> print(numbers) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Alternatively, the caller can use multiple assignment to catch all tuple values individually like so:
a, b, c, d, e, f, g, h, i = create_tuple() print(a, b, c, d, e, f, g, h, i) # 1 2 3 4 5 6 7 8 9
There are many other ways to return a tuple from a function in Python. For example, you can use a generator expression statement instead that is much more concise than the previous code—but creates the same tuple of numbers:
def create_tuple(): ''' Function to return tuple ''' return tuple(i for i in range(10)) numbers = create_tuple() print(numbers) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
With generator expressions, you can dynamically create a tuple by using the syntax
(expression context). You iterate over all elements in a given context “
for i in range(10)“, and apply a certain expression, e.g., the identity expression
i, before adding the resulting values to the newly-created tuple.
In case you need to learn more about generator expressions, feel free to check out the excellent explainer video from Finxter Creator David:
Related Article: A Simple Introduction to Generator Expressions in Python
An interesting way to return a tuple from a function is to use lambda functions.
A lambda function is an anonymous function in Python. It starts with the keyword
lambda, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. Use the
tuple() constructor to create and return a tuple object.
The following code snippet uses a combination of features.
- The lambda function dynamically creates a function object and assigns it to the variable
create_tuple. You can then call the function like before with
- The generator expression creates a tuple and return it at the same time in a single line of code—it cannot get more concise than that.
create_tuple = lambda : tuple(i for i in range(10)) numbers = create_tuple() print(numbers) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.