- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Generate a list of Primes less than n in Python

Suppose we have a number n, we have to generate a list of all prime numbers smaller than or equal to n in ascending order. We have to keep in mind that 1 is not a prime number.

So, if the input is like 12, then the output will be [2, 3, 5, 7, 11].

To solve this, we will follow these steps −

- sieve := a list of size n+1 and fill with True
- primes := a new list, initially blank
- for i in range 2 to n, do
- if sieve[i] is True, then
- insert i at the end of primes
- for j in range i to n, update in each step by i, do
- sieve[j] := False

- if sieve[i] is True, then
- return primes

Let us see the following implementation to get better understanding −

## Example

class Solution: def solve(self, n): sieve = [True] * (n + 1) primes = [] for i in range(2, n + 1): if sieve[i]: primes.append(i) for j in range(i, n + 1, i): sieve[j] = False return primes ob = Solution() print(ob.solve(12))

## Input

12

## Output

[2, 3, 5, 7, 11]

- Related Questions & Answers
- Sum of two elements just less than n in JavaScript
- Largest number less than N with digit sum greater than the digit sum of N in C++
- Nearest prime less than given number n C++
- Count ordered pairs with product less than N in C++
- Python - Check if all the values in a list are less than a given value
- Two Sum Less Than K in Python
- Find the sum of all Truncatable primes below N in Python
- Remove tuples from list of tuples if greater than n in Python
- Python Program to remove elements that are less than K difference away in a list
- Alternate Primes till N in C++?
- C++ Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
- Count pairs with sum as a prime number and less than n in C++
- Find all factorial numbers less than or equal to n in C++
- Print all prime numbers less than or equal to N in C++
- Program to find list of elements which are less than limit and XOR is maximum in Python

Advertisements