Generate a list of 100 random numbers from which delete those numbers which are greater than 20 and less than 50

Viewed 70
import random
res = [ random.randrange(100) for i in range(100) ]
print(res)
final=[]
for i in res :
    if i < 20 and i > 50:
        final.append(i)
print(final)

Above is my code. It is just printing the list of 100 random numbers and it is not working further.

1 Answers

Why not do this?

import random
[i for i in random.sample(range(1, 101), 100) if i not in range(20, 50)]

Sample output:

[10, 82, 96, 71, 85, 13, 58, 5, 9, 89, 1, 88, 69, 55, 51, 61, 73, 86, 54, 83, 93, 15, 67, 72, 3, 53, 17, 16, 8, 95, 50, 79, 94, 87, 66, 64, 14, 91, 92, 75, 2, 99, 100, 97, 76, 4, 80, 70, 60, 56, 90, 74, 98, 11, 6, 65, 62, 57, 63, 81, 19, 78, 59, 68, 77, 18, 7, 12, 52, 84]

As for your code, just change and to or:

import random

res = [random.randrange(100) for i in range(100)]
print(res)
final = []
for i in res:
    if i < 20 or i > 50:
        final.append(i)
print(final)
Related