Home > Back-end >  Can you display integers in a list that are greater than an initial value?
Can you display integers in a list that are greater than an initial value?

Time:03-10

I am trying to print values in a list, that are integers, that are greater than a set initial value, which is also an integer. Would I need a slice to do this?

Here is my code:

n = 3

num_array = [1,2,3,4,5,6,7,8,9,10]

empty_array = []

if any(n > x for n in num_array):
        empty_array.append(x)
    
print(empty_array)

CodePudding user response:

What you wrote doesn't work because:

  1. You're telling it to append x (which doesn't exist outside the generator expression) if at least one value in num_array passes the test given, so any passing value would append only once, not append all the passing values, and
  2. The test is nonsensical (you've never assigned to x, and you're shadowing the definition of n from outside the genexpr with a new one inside it; I'm guessing you intended for x in num_array, not for n in num_array, but since neither work, it's largely irrelevant)

Slicing doesn't help (it's done with index ranges, not value tests, though numpy does offer a solution similar to slicing if you're using it). The typical solution would be a list comprehension (listcomp):

new_array = [x for x in num_array if x > n]

or if you insist on making an empty list and populating it element by element:

new_array = []
for x in num_array:
    if x > n:
        new_array.append(x)

If you were using numpy, you could do this:

import numpy as np

n = 3

num_array = np.array([1,2,3,4,5,6,7,8,9,10])

new_array = num_array[num_array > n]

to get a syntax reminiscent of slicing, but Python built-in types don't support bulk vectorized operations and masking like that.

CodePudding user response:

You could use a list comprehension here:

n = 3
num_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
empty_array = [x for x in num_array if x > n]
print(empty_array)  # [4, 5, 6, 7, 8, 9, 10]

CodePudding user response:

Maybe this is what you wanted?

n = 3

num_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
empty_array = []

for i in num_array:
    if n < i: # If 3 is less than the number the loop is on
        empty_array.append(i)
print(empty_array)
  • Related