Python List Comprehension

Python is known for helping us produce code that is elegant, simple to write, and reads almost as well as plain English. List comprehension is one of the language’s most distinguishing features, allowing us to develop sophisticated functionality with just one line of code. On the other hand, many Python writers struggle to fully utilize the more complex aspects of list comprehension. Sometimes programmers may overuse them, resulting in much less efficient and difficult-to-read code.

Using List Comprehension

newlist = [expression for item in iterable if condition == True]

Here we are showing basic use of list comprehension.

Code

#using for loop to iterate through items in list
numbers = [351739]
num = []
for n in numbers:
num.append(n**2)
print(num)

Output:

[9, 25, 1, 49, 9, 81]

All of this can be accomplished with only single line of code using list comprehension.

Code

#using list comprehension to iterate through list items
numbers = [351739]
num = [n**2 for n in numbers]
print(num)

Output:

[9, 25, 1, 49, 9, 81]

Benefits of Using List Comprehensions

Loops and maps are typically regarded as more Pythonic than list comprehensions. But, rather than taking that judgment at face value, it’s worth considering the advantages of utilizing a list comprehension in Python over the alternatives. We’ll learn about a couple of cases when the alternatives are preferable options later on.

One of the most important advantages of utilizing a list comprehension in Python is that it is a single tool that can be used in various circumstances. We don’t need to adopt a new strategy for each situation. List comprehensions may be leveraged for mapping or filtering and basic list generation.

List comprehensions are regarded as Pythonic, as Python emphasizes simple, effective tools that can be used in many scenarios. As a bonus, we won’t have to remember the appropriate order of parameters when using a list comprehension in Python, as we would when calling map().

List comprehensions are easier to read and grasp than loops since they are more declarative. We must concentrate on how exactly the list is constructed while using loops. We must manually build an empty list, then loop over the list’s entries, and add each one to the list’s end. Instead, using a list comprehension in Python, we can concentrate on what we want to put in the list and allow Python to handle the list generation.

Code

# Import module to keep track of time
import time
# defining function to execute for loop
def for_loop(num):
l = []
for i in range(num):
l.append(i + 10)
return l
# defining function to execute list comprehension
def list_comprehension(num):
return [i + 10 for i in range(num)]
# Giving values to the functions
# Calculating time taken by for loop
start = time.time()
for_loop(10000000)
end = time.time()
print('Time taken by for loop:', (end - start))
# Calculating time taken by list comprehension
start = time.time()
list_comprehension(10000000)
end = time.time()
print('Time taken by list comprehension:', (end - start))

Output:

Time taken by for loop: 7.005999803543091
Time taken by list comprehension: 2.822999954223633

Using List Comprehension to Iterate through String

List comprehension can be used in case of strings also as they are iterables too.

Code

letters = [ alpha for alpha in 'javatpoint' ]
print( letters)

Output:

['j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't']

Using Conditions in List Comprehension

Conditional statements can be used by list comprehensions to change existing lists (or other tuples). We’ll make a list with mathematical operators, numbers, and a range of values.

Code

number_list = [ num for num in range(30if num % 2 != 0]
print(number_list)

Output:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]

Nested List Comprehensions

Nested List Comprehensions are similar to nested for loops in that they are a list comprehension inside another list comprehension. The programme that implements nested loop is as follows:

Code

nested_list = []
for _ in range(3):
# Append an empty sublist inside the list
nested_list.append([])
for __ in range(5):
nested_list[_].append(__ + _)
print(nested_list)

Output:

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

The same result may now be created in less lines of code by utilizing layered list comprehensions.

Code

# Nested list comprehension
nested_list = [[_ + __ for _ in range(5)] for __ in range(3)]
print(nested_list)

Output:

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

List comprehension is a powerful tool for describing and creating new lists based on existing ones. In general, list comprehension is lighter and easier to use than traditional list construction functions and loops. To provide user-friendly code, we should avoid writing large codes for list comprehensions. Every interpretation of the list or other iterables can be recast in a for loop, but not all the for loops can be rebuilt in the framework of list comprehension.

Leave a Reply

Your email address will not be published. Required fields are marked *