In Python, a list is a built-in data structure that represents a collection of data points enclosed in square brackets. Lists can be used to hold any form of data or a mix of data types. In Python, lists are one of the four built-in data structures. Tuples, dictionaries, and sets are examples of other data structures. Further, a list differs from other data types such as int and true in that it is a compound data type that allows you to arrange values together. These values don’t have to be of the same type: they can be a mix of boolean, String, integer, etc.
It’s important to remember that lists are arranged groups of items or objects. Because lists behave like a series, they are called “sequence types” in Python. This means they can be iterated; Strings, tuples, and sets are examples of sequences.
List comprehension encompasses making lists from existing iterables. It can also be regarded as a more user-friendly way of representing for and if loops. It’s a quick technique to make a new list by operating on each item in the old one. List comprehensions are faster than loop comprehensions.
We’ll learn about Python list comprehensions and how to use them in this tutorial.
The syntax is as shown below:
new_resultant_list = [ expression(element) for element in existing_list if condition ]
The list comprehension syntax has three pieces, as shown above: an expression, one or more for loops, and optionally one or more if conditions. The comprehension of the list must be enclosed in square brackets . The initial expression’s result will be saved in the new list. The for loop iterates across the iterable object, which may or may not include the if condition. So we iterate over an iterable, do something with the items (optional! ), and then put them in a list. In certain circumstances, we just take the objects that meet predetermined criteria.
Python List Comprehension’s Benefits
Loops and maps() are typically described as less Pythonic than list comprehensions. Rather than adopting that judgment on faith, it’s worth learning about the advantages of utilizing a list comprehension in Python over the alternatives. You’ll learn about a couple of cases where the alternatives are a better option later on.
- Fewer lines of code are required.
- The iterative statement is converted to a formula.
- Loops are inefficient in both time and space.
- It has a simple and elegant syntax for constructing new lists from existing lists or iterables.
When should you avoid using list comprehension?
List comprehension memorizes the full output list. For short or medium-sized lists, this is okay or even preferable because it speeds up the process. When working with big lists, list comprehension should be avoided (e.g., 1 billion entries). Due to the high RAM requirements, it may cause your computer to crash.
A better option is a generator that does not build a large data structure in memory for such enormous lists. When objects are used, a generator makes them. The generator discards the objects after they have been used. We can ask for the next item in an iterable till we reach the end and save a single value at a time using a generator.
Comparison between a List Comprehension and For Loop In Python
Let’s say we want to separate the letters in the word ‘codeunderscored’ and put them as list items. Using for loop is the first thing that springs to mind.
# Example: String Iteration Using for Loop letter_distribution =  for letter in 'codeunderscored': letter_distribution.append(letter) print(letter_distribution)
Upon running the program, the following is the result:
However, List Comprehension in Python makes this problem easier to address. List comprehension refers to a sophisticated approach to defining and creating new lists from existing ones. Let’s look at how to write the above program using list comprehensions.
# Example: String Iteration Using List Comprehension letter_distribution = [ letter for letter in 'codeunderscored' ] print( letter_distribution)
Upon running the program, the following is the result:
In the example above, the variable letter_distribution is given a new list, which includes the items of the iterable string ‘codeunderscored .’ To get the output, we use the print() function.
List Comprehension Syntax
[expression for item in list]
[ letter for letter in 'codeunderscored' ]
We can see where list comprehensions are utilized now. codeunderscored is a string, not a list, as you may have seen. This is the power of understanding lists. When it receives a string or tuple, it can recognize it and treat it as a list.
You can use loops to accomplish this. Not all loops, however, can be expressed as a list comprehension. However, as you become more familiar with list comprehensions, you’ll substitute loops with this elegant syntax.
Lambda functions vs. List comprehensions
List comprehension isn’t the sole method of working with lists. You can use several built-in and lambda functions to generate and alter lists with fewer lines of code.
# Example: Using Lambda functions within Lists letter_distribution = list(map(lambda code: code, 'codeunderscored')) print(letter_distribution)
On running the program above, the following is the result:
On the other hand, list comprehensions are usually more human-readable than lambda functions. When list comprehensions are utilized, it is easy to comprehend what the programmer was trying to do.
List comprehension with conditionals
Conditional statements find use in list comprehensions to modify lists that are already existing or other tuples.
We’ll make a list with mathematical operators, numbers, and a range of values ().
# Example: Using if with Comprehension List num_var_list = [ x_var for x_var in range(50) if x_var % 3 == 0] print(num_var_list)
When we run the program as mentioned earlier, the following is the result:
# Example: Nested IF with List Comprehension num_var_list = [x_var for x_var in range(99) if x_var % 3 == 0 if x_var % 5 == 0] print(num_var_list)
List the following comprehension checks:
- Is the number x_var divisible by three?
- Is x_var a multiple of five or not?
If x_var meets both criteria, it is added to num_var_list.
Example: if…else with List Comprehension
code_result = ["Divisible by 3" if x_var %3==0 else "Even" for x_var in range(15)] print(code_result)
When we run the program mentioned above, the following is the result:
List comprehension will be tested on the fifteen numbers from 0 to 15. ‘Divisible by 3’ is added to the code_result list if x_var is divisible by three. Odd is appended if not.
List comprehension with nested loops
Assume we need to compute the transpose of a matrix, which necessitates the use of nested for loops. First, let’s look at how it’s done using a typical for loop.
# Example: Matrix Transposition Using Nested Loops var_transposed =  var_matrix = [[11, 12, 13, 14], [14, 15, 16, 18]] for i in range(len(var_matrix)): var_transposed_row =  for row in var_matrix: var_transposed_row.append(row[i]) var_transposed .append(var_transposed_row) print(var_transposed )
The above code employs two for loops to find the matrix’s transpose.
Within a list comprehension, we can also execute nested iteration. We’ll use a nested loop inside a list comprehension to find the transpose of a matrix in this section.
# Example: Using List Comprehension to Transpose a Matrix var_matrix = [[1, 2], [3,4], [5,6], [7,8]] var_transpose = [[row[x_var] for row in var_matrix] for x_var in range(2)] print(var_transpose)
upon running the program above, the following is the result:
We have a variable matrix with four rows and two columns in the above program. Now, we need to find the matrix’s transpose. We have utilized a list comprehension to accomplish this.
List comprehension nested loops are not the same as regular nested loops. For x_var in range(2) is executed before row[x_var] for row in matrix in the given program. As a result, after assigning a value to x_var, the item directed by row[x_var] is appended to the transpose variable.
Example: Using List comprehension to create a new list from an existing list
When you wish to build a new list based on the values of an existing list, list comprehension has a shorter syntax. For example, let us say you wish to create a new list from a list of laptops that only includes laptops that begin with the letter “c.” You’ll have to build a for statement with a conditional test inside if you don’t have list comprehension:
laptops = ["apple", "chrome book", "HP", "Lenovo", "IBM"] filtered_laptops_list =  for _lap in laptops: if "c" in _lap: filtered_laptops_list.append(_lap) print(filtered_laptops_list)
You can accomplish all of the code shown above with only one line of code using list comprehension:
laptops = ["apple", "chrome book", "HP", "Lenovo", "IBM"] filtered_laptops_list = [_lap for _lap in laptops if "c" in _lap] print(filtered_laptops_list)
The syntax is as follows:
new_filtered_list = [expression for item in iterable if condition == True]
The outcome is a new list, with the previous list remaining untouched.
The condition acts as a filter, accepting those elements that evaluate True. The following example just accepts laptop items that are not “HP”:
laptops = ["apple", "chrome book", "HP", "Lenovo", "IBM"] filtered_laptops_list = [_lap for _lap in laptops if _lap != "HP"]
If _lap!= “HP,” the condition returns True for all entries other than “HP,” resulting in a new list that contains all laptops except “HP.” The following condition is optional and can be left out:
Example with no if clause:
filtered_laptops_list = [_lap for _lap in laptops]
Any iterable object, such as a list, tuple, or set, can be used as the iterable. For example, you can generate an iterable using the range() function:
code_list = [x_var for x_var in range(8)]
The same example above can be expressed with a twist. For instance, only numbers less than five are acceptable:
code_list = [x_var for x_var in range(8) if x_var < 5]
The expression is the iteration’s current item, but it’s also the result, which you can change before it becomes a list item in the new list. For example, make the following changes to the new list’s values:
new_filtered_list = [x_var.upper() for x_var in laptops]
You have complete control over the outcome. A case in hand is setting all of the new list’s values to ‘code’ as follows:
new_filtered_list = ['code' for x_var in laptops]
Conditions can also be included in the expression, not as a filter, but to influence the result. Examine the following requirement to replace “chrome book” with “Toshiba”:
new_filtered_list = [x_var if x_var != "chromebook" else "Toshiba" for x_var in laptops]
The expression in the preceding section simply indicates as follows:
“If it’s not a chrome book, return it; if it is, return the Toshiba.”
Important Points to Remember
List comprehension applies a sophisticated method to defining and creating new lists from existing ones.
List comprehension is, by convention, more compact and faster than standard functions and loops for generating lists.
To keep the code user-friendly, we should avoid creating very long list comprehensions in one line.
Remember that every list comprehension can be rebuilt in the form of a for loop, but not every for loop can be rewritten as a list comprehension.
Example: the difference between for loops and list comprehension
# First, import the necessary modules import time # definition of the function for implementing the for loop def eval_for_loop(n_var): result_var =  for i in range(n_var): result_var.append(i**2) return result # definition of the function for implementing the list comprehension def list_comprehension(n_var): return [i**2 for i in range(n_var)] # Driver Code # Evaluating the time taken by the eval_for_loop() start_var = time.time() for_loop(10**6) end_var = time.time() # showing the time taken by the eval_for_loop() print('Time taken for_loop:',round(end_var-start_var,2)) # Evaluating the time taken by the list_comprehension() start_list_var = time.time() list_comprehension(10**6) end_list_var = time.time() # showing the time taken by the eval_for_loop() print('Time taken for list_comprehension:',round(end_list_var-start_list_var ,2))
Example: How to flatten a List through List Comprehension
You can engage list comprehension to flatten a list that consists of many lists into a single list.
var_matrix=[[11, 12, 13], [14, 15, 16], [17, 18, 19, 20, 21]] var_flattened_list=[num for row in var_matrix for num in row] print(var_flattened_list)
Python is known for pushing programmers and developers to write code that is efficient, easy to understand, and almost as easy to read. The python list and list compression features are two of the language’s most distinguishing features, which you can use to build extensive functionality with just one line of code.
List comprehensions are very useful in generating novel lists from iterables such as tuples, arrays, strings, and lists. A list comprehension comprises brackets that contain the expression that is run for each element, as well as a for loop that iterates over each element.