Return List from Function - Python
In Python, functions can return a wide variety of data types and we can return list too. Our task is to return a list from a Python function. We'll do this using different techniques—returning static data, computed values and generator-based lists, through short, clear examples.
We can simply construct the list within function and return it. This method is both concise and readable. Example:
def get_list():
li = [1, 2, 3, 4, 5]
return li
res = get_list()
print(res)
Output
[1, 2, 3, 4, 5]
Exaplanation: The function get_list() creates a list li with the elements [1, 2, 3, 4, 5] and returns it to the caller. When the function is called, the returned list is assigned to the variable res, which is then printed.
Examples of Returning a List from a Function
Example 1: Return a Static List
This function returns a predefined list of fruit names, demonstrating how to return a constant list without computation.
def get_fruits():
return ["apple", "banana", "cherry"]
f = get_fruits()
print(f)
Output
['apple', 'banana', 'cherry']
Explanation: The list is created inside the function and returned as-is when the function is called.
Example 2: Return a Computed List
This function calculates the square of each number from 0 to n-1 and returns them in a list.
def sq(n):
r = []
for i in range(n):
r.append(i * i)
return r
print(sq(5))
Output
[0, 1, 4, 9, 16]
Explanation: It iterates from 0 to n-1, computes i*i for each value, and collects the results in the list r.
Example 3: Using List Constructor with a Generator
A more advanced approach involves using a generator expression within the list constructor to return a list.
def generate_list(n):
return list(i for i in range(n) if i % 2 == 0)
res = generate_list(10)
print(res)
Output
[0, 2, 4, 6, 8]
Explanation:
- The code uses list constructor to create a list of even number from 0 to 9....
- It then return the list and we print them by calling the function.
Related Articles: