Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a print statement in a complicated expression?

I have the following code:

prime_numbers = [number for number in range(2, 101) 
if all(number % div != 0 
for div in range(2, int(number**0.5) + 1))]

How would I add a print statement for number?

UPDATE:Thank you everyone who responded except of course the people who downvoted. This is obviously lousy code. I know that. It was a question a student asked and I wanted to provide a complete explanation. I believe, if you are going to use this code the best way to adjust it is as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

primes = []
[primes. Append(number)

for number in range(2, 101) 
if all(number %
div != 0 for div in range(2, int(number**0.5) + 1))]

print(primes)

>Solution :

Technically since the truthiness of print(number) is False (print() returning None), you can enjoy it’s effect and use an or to get the result in the list still.

prime_numbers = [
    print(number) or number
    for number
    in range(2, 101)
    if all(
        number % div != 0
        for div
        in range(2, int(number**0.5) + 1)
    )
]
print(prime_numbers)

Giving you:

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
[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]

However, comprehensions are discouraged for side effects like this (at least by me). You might want to just use a more traditional for loop.

See also: Is it Pythonic to use list comprehensions for just side effects?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading