Aarif1430
Aarif1430

Reputation: 155

List comprehension for finding all prime numbers from a range of numbers?

[x for x in range(1,100) if all(x%y for y in range(2,x))]

Not able to understand how above code is returning correct results, Instead it should be

[x for x in range(1,100) if all(x%y!=0 for y in range(2,x))]

The reason is if all is True if only one of the condition is True.

Upvotes: 1

Views: 806

Answers (1)

wim
wim

Reputation: 362756

Non-zero integers are considered truthy in a boolean context, so the code snippets are equivalent.

Note that this algorithm incorrectly classifies 1 as a prime number.

Upvotes: 4

Related Questions