How to Return List in Python: 3 Top Methods Explained

by | Python

The return statement plays a pivotal role in Python. It’s what lets your functions communicate with the rest of your code.

And one thing you’ll have to return sooner or later in your applications is a list.

To return a list in Python, you can use the return statement followed by the Python list variable name. You can also use a list comprehension or lambda function to return a list for shorter and cleaner code!

Now that you know how to return a list, it’s time to practice and explore further!

how to return list in python

3 Ways to Return a List from a Function in Python

There are many techniques you can use to return a list from a function in Python. Some of these techniques include:

  • Return Statement

  • List Comprehension

  • Lambda Functions

Let’s take a look at how they work.

1. How to Return a List Using the Return Statement

The most common way to return a list from a Python function is to create the list and return it using the return statement. Here’s how you can use it.

Step 1: Create a User-Defined Function

You can create a user-defined function by using the def keyword. Suppose you need a function that returns the square of all the integers in a given list. The function takes one integer list as a parameter and returns a new list that contains the squares of the original list.

Here’s the Python code to define this function:

Function defnition

The above code defines a function return_squares() that takes one parameter integer_list. This parameter represents the list of integers you want to square.

Step 2: Implement the Function Logic and Store the Result In a Variable

A for loop in Python can be used to traverse the list’s elements and calculate the square of each element in the integer list. After this, it adds the squared element to the squared_list variable one by one.

Here’s the code:

def return_squares(int_list:list):
    squared_list = []
    
    for int in int_list:
        squared_list.append(int**2)
        
    return squared_list

Step 3: Enlist the Return Statement

Finally, the return statement is used to pass the squared_list to the calling code. Once the return statement is executed, function execution is terminated and control is transferred back to the calling code. No further code inside the function block is executed.

Let’s put our new function to the test in an example.

print(squared_list([2, 5, 8, 14]))
print(squared_list([11, 9, 22])

Output:

Square of numbers

Now, we can see our function returns a list of squared elements!

2. How to Return a List by Using List Comprehension

List comprehension is a powerful Python feature that allows you to generate a new list from an existing list in a single line. By using list comprehension in your function, you can avoid using a for loop and the function’s returned list will be created directly.

The syntax for list comprehension is:

expression for iterator in iterable

where:

  • expression is the statement or value you want to return

  • iterator is the variable that represents the current element of the list

  • iterable is the list you want to iterate.

Suppose you need a function that returns a list of even numbers from 1 to n where n is an integer. The function should use list comprehension. Here’s the Python code using list comprehension:

def return_even_numbers(num):
    return [x for x in range(num) if x%2 == 0 ]

print(return_even_numbers(12))
print(return_even_numbers(40))

Output:

Using List Comprehension

The above function return_even_numbers() creates a new list even_numbers using list comprehension. The expression inside the square brackets in the list comprehension is n if n%2 == 0, which means the variable n is added to the output list when it’s an even number.

3. How to Return a List Using a Lambda Function

Lambda functions are powerful one-line expressions in Python that are often used for simple, inline operations like arithmetic calculations. can also be used to create functions that will return a list. If you need a custom function that creates a list and want to do so using a lambda function, follow these steps:

  • Define your list creation logic.

  • Create your lambda function.

  • Call your lambda function and provide inputs.

Here’s an example in the following code:

create_list = lambda x, y : [ i for i in range(0, x, y)]

print(create_list(25, 3))
print(create_list(47, 9))

Output:

Lambda Function returning a list

In the above example, we created a lambda function object that takes in two values: a range and a step. It creates a list of numbers from zero to the range equally spaced by the specified step value.

When to Use Each Method to Return a List

Each method has its strengths, and you should consider using them based on the complexity and the requirements of your program. Let’s discuss the best use case for each method.

The Return Statement

The return statement is straightforward and easy to understand. This method should be your primary method for simple functions, especially if you’re a beginner to Python.

For instance, suppose you’re trying to implement a function that takes in two lists and returns a new list containing the sum of elements from the matching indices in the original lists. The return statement would be the best option as a one-liner list comprehension or lambda function might be a bit too complex.

List Comprehension

When you want to return a manipulated list but only use one line of code, list comprehension is your go-to method. This is great for functions with a few lines of code, and the list comprehension syntax can generate the needed list in one.

Lambda functions

If you need a simple, reusable, one-line function to create a list, a lambda function may be used. The lambda function is especially useful with python functions like map() and filter(), or any other function that expects a function as an argument.

Final Thoughts

Returning lists in Python can be as complex or as basic as you need it to be. Whether you’re returning a single list from a function, returning a list of lists, or even returning a single list that spans multiple rows of data, it only needs a little bit of Python knowledge to make it happen!

We hope we’ve provided you with the necessary knowledge in this article. Good luck and Happy coding!

If you would like to learn more about Data Wrangling Functions In Python check out the below video:

Frequently Asked Question

How do you assign list items to a variable after returning them?

You can assign the items in a list to individual variables using a technique called list destructuring. Here’s an example:

def test_func():
    return ['Angela', 'Engineer', 22]

name, job,age = test_func()
print(name, job, age)

Output:

List Destructuring

In the example above, we unpacked the multiple return values from the list and placed them into individual variables using restructuring. You can use this with other data structures like sets, tuples, etc.

How do you return a tuple from a function?

You can return a tuple from a function by creating a tuple inside the function and placing the tuple name inside the return variable. You can also return a tuple by placing the Python objects you want to return next to the return keyword and separating them using commas.

This is a great way to return multiple values from a function, here’s an example:

def ret_tuple():
    return 22, "apple", False

print(ret_tuple())

Output:

Returning A Python Tuple

As we can see, the return keyword takes the comma separated values in front of it and packs them into a tuple, which it returns.

How to Return List of Tuples From Two Lists

While returning lists is one way to output data from a function, returning a list of tuples is another way to provide your data. When you want to return multiple lists as a single list of tuples, you can use a built in function called zip() to join them together.

Here’s an example of how to use the zip function:

def zip_list(list1, list2):
    return list(zip(list1, list2))

print(zip_list(['Messi', 'LeBron', 'Nadal'], ['Football', 'Basketball', 'Tennis']))

Output:

[('Messi', 'Football'), ('LeBron', 'Basketball'), ('Nadal', 'Tennis')]

As we can see, when you implement the function above and call it with the two lists, the function will return a list of tuples.

How to Flatten a Multi-Dimensional Python List

A multi-dimensional Python list is nothing more than a list of lists. When you need to flatten such a list, you can use various techniques. Two popular ones include the itertools module and list comprehension.

Here’s an example of how to flatten a list using list comprehension:

def flatten(L):
  return [L] if not isinstance(L, list) else [x for X in L for x in flatten(X)]

nested_li = [[3, 76], [12, 49], 3, [15, 16, [1, 2, 14]]]
flat_list = flatten(nested_li)

print(flat_list)

Output:

Flattening a Nested List

This method above works for both regular and irregular nested lists.

author avatar
Sam McKay, CFA
Sam is Enterprise DNA's CEO & Founder. He helps individuals and organizations develop data driven cultures and create enterprise value by delivering business intelligence training and education.

Related Posts