Advantages of list comprehension in Python

Python List Comprehension

Python is renowned for encouraging developers and programmers to write efficient, easy-to-understand, and almost as simple-to-read code. One of the most distinctive aspects of the language is the python list and the list compression feature, which one can use within a single line of code to construct powerful functionality.

List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Syntax:



newList = [ expression[element] for element in oldList if condition ]

Advantages of List Comprehension

  • More time-efficient and space-efficient than loops.
  • Require fewer lines of code.
  • Transforms iterative statement into a formula.

List Comprehensions vs For Loop

There are various ways to iterate through a list. However, the most common approach is to use the for loop. Let us look at the below example:

Python3




# Empty list
List = []
# Traditional approach of iterating
for character in 'Geeks 4 Geeks!':
List.append[character]
# Display list
print[List]

Output:

[G, e, e, k, s, , 4, , G, e, e, k, s, !]

Above is the implementation of the traditional approach to iterate through a list, string, tuple, etc. Now list comprehension does the same task and also makes the program more simple.

List Comprehensions translate the traditional iteration approach using for loop into a simple formula hence making them easy to use. Below is the approach to iterate through a list, string, tuple, etc. using list comprehension.

Python3




# Using list comprehension to iterate through loop
List = [character for character in 'Geeks 4 Geeks!']
# Displaying list
print[List]

Output:

[G, e, e, k, s, , 4, , G, e, e, k, s, !]



The list comprehensions are more efficient both computationally and in terms of coding space and time than a for loop. Typically, they are written in a single line of code. The below program depicts the difference between for loops and list comprehension based on performance.

Python3




# Import required module
import time
# define function to implement for loop
def for_loop[n]:
result = []
for i in range[n]:
result.append[i**2]
return result
# define function to implement list comprehension
def list_comprehension[n]:
return [i**2 for i in range[n]]
# Driver Code
# Calculate time takens by for_loop[]
begin = time.time[]
for_loop[10**6]
end = time.time[]
# Display time taken by for_loop[]
print['Time taken for_loop:',round[end-begin,2]]
# Calculate time takens by list_comprehension[]
begin = time.time[]
list_comprehension[10**6]
end = time.time[]
# Display time taken by for_loop[]
print['Time taken for list_comprehension:',round[end-begin,2]]

Output:

Time taken for_loop: 0.56 Time taken for list_comprehension: 0.47

From the above program, we can see list comprehensions are quite faster than for loop.

Nested List Comprehensions

Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops. Below is the program which implements nested loop:

Python3




matrix = []
for i in range[3]:
# Append an empty sublist inside the list
matrix.append[[]]
for j in range[5]:
matrix[i].append[j]
print[matrix]

Output:

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Now by using nested list comprehensions same output can be generated in fewer lines of code.

Python3




# Nested list comprehension
matrix = [[j for j in range[5]] for i in range[3]]
print[matrix]

Output:

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

List Comprehensions and Lambda

Lambda Expressions are nothing but shorthand representations of Python functions. Using list comprehensions with lambda creates an efficient combination. Let us look at the below examples:



Python3




# using lambda to print table of 10
numbers = []
for i in range[1, 6]:
numbers.append[i*10]
print[numbers]

Output:

[10, 20, 30, 40, 50]

Here, we have used for loop to print table of 10.

Python3




numbers= [i*10 for i in range[1,6]]
print[numbers]

Output:

[10, 20, 30, 40, 50]

Now here, we have used only list comprehension to display table of 10.

Python3




# using lambda to print table of 10
numbers = list[map[lambda i: i*10, [i for i in range[1,6]]]]
print[numbers]

Output:

[10, 20, 30, 40, 50]

Finally, we use lambda + list comprehension to display the table of 10. This combination is very useful to get efficient solutions in fewer lines of code for complex problems.

Conditionals in List Comprehension

We can also add conditional statements to the list comprehension. We can create a list using range[], operators, etc. and cal also apply some conditions to the list using the if statement.

Below are some examples which depict the use of list comprehensions rather than the traditional approach to iterate through iterables:

Example 1: Display square of numbers from 1 to 10.

Python3




# Getting square of even numbers from 1 to 10
squares = [n**2 for n in range[1, 11] if n%2==0]
# Display square of even numbers
print[squares]

Output:

[4, 16, 36, 64, 100]

Example 2: Display even elements from a list of random numbers.

Python3




# Assign matrix
twoDMatrix = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# Generate transpose
trans = [[i[j] for i in twoDMatrix] for j in range[len[twoDMatrix]]]
print[trans]

Output:

[++++[+10, 40, 70], [20, 50, 80], [30, 60, 90]]

Example 3: Toggle case of each character in a string.

Python3




# Initializing string
string = 'Geeks4Geeks'
# Toggle case of each character
List = list[map[lambda i: chr[ord[i]^32], string]]
# Display list
print[List]

Output:

[g, E, E, K, S, \x14, g, E, E, K, S, \x01]

Example 4: Reverse each string in a tuple.

Python3




# Reverse each string in tuple
List = [string[::-1] for string in ['Geeks', 'for', 'Geeks']]
# Display list
print[List]

Output:

['skeeG', 'rof', 'skeeG']

Example 5: Display the sum of digits of all the odd elements in a list.

Python3




# Explicit function
def digitSum[n]:
dsum = 0
for ele in str[n]:
dsum += int[ele]
return dsum
# Initializing list
List = [367, 111, 562, 945, 6726, 873]
# Using the function on odd elements of the list
newList = [digitSum[i] for i in List if i & 1]
# Displaying new list
print[newList]

Output:

[16, 3, 18, 18]

Key Points

  • Comprehension of the list is an effective means of describing and constructing lists based on current lists.
  • Generally, list comprehension is more lightweight and simpler than standard list formation functions and loops.
  • We should not write long codes for list comprehensions in order to ensure user-friendly code.
  • Every comprehension of the list can be rewritten in for loop, but in the context of list interpretation, every for loop can not be rewritten.



Article Tags :
Python
Technical Scripter
python-list
Technical Scripter 2020
Practice Tags :
python-list
Read Full Article

Video liên quan

Chủ Đề