[Solved] How to convert a for loop in list comprehension in Python?

Introduction

List comprehension is a powerful tool in Python that allows you to quickly and easily convert a for loop into a single line of code. This can be especially useful when dealing with large datasets or complex operations. In this article, we will discuss how to convert a for loop into a list comprehension in Python. We will also discuss the advantages and disadvantages of using list comprehension over for loops. Finally, we will provide some examples of how to use list comprehension to solve common problems.

Solution

#For loop
my_list = []
for i in range(10):
my_list.append(i)

#List comprehension
my_list = [i for i in range(10)]


Could you have been thinking of something like this?

def isPrime(n):
    if n < 2: return None
    factors = [ i for i in range(2, n) if n%i == 0 ]
    return True if not factors else False

print( [ i for i in range(1, 100) if isPrime(i) ] )
#PRINTS:
[2,  3,  5,  7,  11, 13, 17, 19, 23, 29, 31, 37, 
 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

1

solved How to convert a for loop in list comprehension in Python?