In this tutorial, we will learn how to return a list from a function and how to use this list in another function in Python.
Returning a list from a function is a typical use case in Python programming where the return type is a list. A list in Python is a mutable and ordered collection of elements enclosed within square brackets [].
Step 1: Define a function that returns a list
First, you need to define a function that creates and returns a list. Let’s create a simple function that returns a list of numbers from 1 to n:
1 2 3 |
def create_list(n): numbers = [i for i in range(1, n + 1)] return numbers |
In this function, we use list comprehension to generate a list of numbers from 1 to n and then return the list.
Step 2: Define another function that accepts a list as an argument
Next, define the function that accepts a list as an argument and performs an operation on the elements of the list. In our example, let’s create a function that calculates the sum of the elements in the list:
1 2 3 |
def calculate_sum(numbers): total = sum(numbers) return total |
Our function takes a list of numbers as an argument and returns the sum of the elements in the list.
Step 3: Call the functions and use the returned list as an argument
Now you need to call the first function that returns the list and pass the returned list to the second function.
1 2 3 4 |
n = 5 numbers = create_list(n) result = calculate_sum(numbers) print(f"The sum of numbers from 1 to {n} is: {result}") |
In this code block, we call the create_list function with an argument (n = 5) which returns the list of numbers from 1 to 5. Then we pass this list to the calculate_sum function. The result of the calculations is printed on the screen.
The output should be:
The sum of numbers from 1 to 5 is: 15
Full code example:
Here’s the full Python code to return a list from one function to another using the example described above:
1 2 3 4 5 6 7 8 9 10 11 12 |
def create_list(n): numbers = [i for i in range(1, n + 1)] return numbers def calculate_sum(numbers): total = sum(numbers) return total n = 5 numbers = create_list(n) result = calculate_sum(numbers) print(f"The sum of numbers from 1 to {n} is: {result}") |
Conclusion
In this tutorial, we learned how to return a list from a function and use it as an argument in another function in Python programming. By understanding how to return and manipulate lists from functions, you can leverage the power and flexibility of lists in Python to optimize your code.