Create and Print a List of Prime Numbers in Python

Introduction

Prime numbers mean the numbers which can be divided only by 1 or the number itself(e.g 2, 3, 5, 7, 11, etc). Today, we will learn how to create and print a list of prime numbers in Python. We will create a list of prime numbers which are under 50 using a function. We will store the returned prime numbers in a list and will print that list simply.

Code to Create and Print a List of Prime Numbers in Python

1. With Function

def prime_numbers(n):
    primes = []
    for i in range(2, n + 1):
        for j in range(2, int(i ** 0.5) + 1):
            if i%j == 0:
                break
        else:
            primes.append(i)
    return primes

prime_list = prime_numbers(50)
print(prime_list)

Output:

Output to Create and Print a List of Prime Numbers in Python

2. One-Liner

print([i for i in range(2, 50) if 0 not in [i%n for n in range(2, i)]])

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Conclusion

We have learned how can we create and print a list of prime numbers in Python. The logic behind creating a list of prime numbers is simple, we need to check all the numbers whether they are prime or not before we append them to the list.

We hope you find this article on Create and Print a List of Prime Numbers in Python helpful for you.

Thank you for visiting our website.


Also Read:

Share:

Author: Yogesh Kumar