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:
- You're telling it to
append
x
(which doesn't exist outside the generator expression) if at least one value innum_array
passes the test given, so any passing value wouldappend
only once, not append all the passing values, and - The test is nonsensical (you've never assigned to
x
, and you're shadowing the definition ofn
from outside the genexpr with a new one inside it; I'm guessing you intendedfor x in num_array
, notfor 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)