Do you need to create a function that returns a list but you don’t know how? No worries, in sixty seconds, you’ll know! Go! 👇
Python Return List Basic
A Python function can return any object such as a list. To return a list, first create the list object within the function body, assign it to a variable
your_list, and return it to the caller of the function using the keyword operation “
For example, the following code creates a function
create_list() that iterates over all numbers 0, 1, 2, …, 9, appends them to the list
your_list, and returns the list to the caller of the function:
def create_list(): ''' Function to return list ''' your_list =  for i in range(10): your_list.append(i) return your_list numbers = create_list() print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Note that you store the resulting list in the variable
numbers. The local variable
your_list 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_list, Python will raise a
>>> print(your_list) Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 9, in <module> print(your_list) NameError: name 'your_list' is not defined
To fix this, simply assign the return value of the function — a list — to a new variable and access the content of this new variable:
>>> numbers = create_list() >>> print(numbers) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Return List with List Comprehension
There are many other ways to return a list in Python. For example, you can use a list comprehension statement instead that is much more concise than the previous code—but creates the same list of numbers:
def create_list(): ''' Function to return list ''' return [i for i in range(10)] numbers = create_list() print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
List comprehension is a very useful Python feature that allows you to dynamically create a list by using the syntax
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 list.
In case you need to learn more about list comprehension, feel free to check out my explainer video:
Python Return List Using Lambda Function
An interesting way to return a list 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 square bracket notation
[ ... ] or the
list() constructor to create and return a list 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_list. You can then call the function like before with
- The list comprehension expression creates a list and return it at the same time in a single line of code—it cannot get more concise than that.
create_list = lambda : [i for i in range(10)] numbers = create_list() print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Python Return List of Objects
You can create a function that returns a list of objects using the list comprehension expression in combination with the return keyword like so in your function body:
return [Example() for _ in range(n)]
Here’s a minimal example:
class Example(object): pass def return_objects(n): return [Example() for _ in range(n)] print(return_objects(3))
👉 Recommended Tutorial: How to Create a List of Objects in Python?
Python Return List as String
Here’s a minimal example:
def list_to_string(my_list): return ' '.join([str(x) for x in my_list]) print(list_to_string(['Alice', 'is', 18, 'years old'])) # Alice is 18 years old
Note that you can also use a generator expression inside the
join() method call instead of a list comprehension to save an additional two (!) characters. 🚀
def list_to_string(my_list): return ' '.join(str(x) for x in my_list)
There are many more ways to convert a list to a string as shown in the following tutorial. Check it out! 👇
👉 Recommended Tutorial: Python Convert List to String
Python Return List of Tuples From Two Lists
Challenge: How to create a function that takes two lists of same length and returns a list of tuples whereas the i-th elements of both lists are bundled together in a single tuple of the returned list?
To return a list of tuples from two lists use the expression
list(zip(list_1, list_2)) that first bundles together the i-th elements of both lists using the
zip() function to obtain an iterable of tuples and second convert the result to a list of tuples using the built-in
Here’s a minimal example of a function that returns a list of tuples from two lists:
def bundle(list_1, list_2): return list(zip(list_1, list_2)) print(bundle([1, 2, 3], ['a', 'b', 'c'])) # [(1, 'a'), (2, 'b'), (3, 'c')]
This approach will also work if the lists have different lengths.
And a similar approach will also work if you have more than two or even a variable number of list arguments for the function by using the asterisk operator
* like so:
def bundle(*lists): return list(zip(*lists)) print(bundle([1, 2, 3], ['a', 'b', 'c'])) # [(1, 'a'), (2, 'b'), (3, 'c')] print(bundle([1, 2], [3, 4], [5, 6], [7, 8])) # [(1, 3, 5, 7), (2, 4, 6, 8)]
Python is beautiful, isn’t it?
You may be interested in our video and blog guide on the
zip() function. Check it out! 👇
👉 Recommended Tutorial: Python Zip Function
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.
Q: How do you tell an introverted computer scientist from an extroverted computer scientist? A: An extroverted computer scientist looks at your shoes when he talks to you.
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.