This question already has answers here:
Pythonic way of checking if a condition holds for any element of a list
(3 answers)
Closed 8 years ago.
how do you detect if a value held in a list is negative, I just need to find out if there is a value that is negative, so far i have this:
if list[range(list)] < 0
But surely this will only detect if all the values in list are negative.How would i go about doing this?
Also, how would i be able to detect if a value in the list was not an integer, for example it was a floating point number, or even a character
Thanks
You can use any function, like this
if any(item < 0 for item in my_list):
For example,
print any(item < 0 for item in [0, 1, 2])
# False
print any(item < 0 for item in [0, 1, -2])
# True
We use a generator expression in the any function. It returns True, if any of the item is lesser than 0.
Related
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
The code below works such that an array is an input in a function. This 2 element array is iterated such that it would stop if the difference between the new and previously iterated array values equals zero (or it is intended to work as such). Note that the function below is just a pseudo function.
Is using a "OR" and "AND" operator appropriate for what I want. If so, which is best to use and if not, what is a better method?
def func(array):
counter = 0
diff = True
array_i = array
while diff:
array_f = array_i + 1/array_i
diff = abs(array_i[0] - array_f[0]) or abs(array_i[1] - array_f[1]) > 0
array i = array_f
counter += 1
return array_i, counter
The logical operator or is used when you want to check a condition or another condition. The and operator is when both are to be combined.
Checks to see if either one or the other are greater than zero.
abs(array_i[0] - array_f[0]) > 0 or abs(array_i[1] - array_f[1]) > 0
checks to see if both are greater than zero.
abs(array_i[0] - array_f[0]) > 0 and abs(array_i[1] - array_f[1]) > 0
This question already has answers here:
Python: max/min builtin functions depend on parameter order
(3 answers)
Closed 3 years ago.
Can anyone tell me why looking for the minimum value in a list using min(list) is not working when NaN is the first element of the list? The same applies when using max(list)
import math
y = [float('nan'),1,2,3,0,float('nan'),6,7,8,9]
print(y)
print(math.isnan(y[0]))
print(min(y))
w = [10,1,2,3,0,float('nan'),6,7,8,9]
print(w)
print(min(w))
print(math.isnan(w[5]))
Any comparison operation performed on nan with a number will return False.
print(y[1] > y[0])
print(y[1] < y[0])
Results in
False
False
If the built-in function follows the same logic while comparing the elements the above behavior is easily explained. If the first element is selected as min element any comparison afterward will be False hence returning nan as min element.
You can filter y or w to ignore nan:
print(min(i for i in y if not math.isnan(i)))
# 0
This question already has answers here:
if/else in a list comprehension
(12 answers)
Is it possible to use 'else' in a list comprehension? [duplicate]
(6 answers)
Closed 3 years ago.
I'm just getting started with Python and was reading about list comprehensions.
The following code:
my_list = [x ** x for x in range(1,11) if x % 2 == 0]
print(my_list)
... produces this output:
[4, 256, 46656, 16777216, 10000000000]
I then tried this code:
my_list = [x ** x for x in range(1,11) if x % 2 == 0 else 7]
print(my_list)
... but I got a syntax error starting at the second "e" in else.
Can someone explain why I'm getting a syntax error? I'd like to have the list create a list of even squares based on the value of the base (x), and to have the value "49" if the list value is not an "even number" square.
In this case, you would want
my_list = [x ** x if x % 2 == 0 else 49 for x in range(1,11)]
If you use an if at the end of a list comprehension like that, it is used to select which elements to include. If you want a different result depending on the case, you need to use a ternary if at the beginning instead.
For more info, take a look at the docs here. To quote:
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
There is no support for else here, presumably because a ternary if (if condition then foo else bar) in the 'body' of the comprehension already accomplishes this and "There should be one-- and preferably only one --obvious way to do it."
This question already has answers here:
Pythonic way of checking if a condition holds for any element of a list
(3 answers)
Closed 4 months ago.
Suppose I have n values in a list x = [1.2, -0.4, 3.5, ....]
I need to check if at least one of them is below zero.
So basically, if I had only two values, I'd have written
if x[0]< 0 or x[1] < 0
But now, I need to use the same or operator within a loop so as to check each one of the values in the list.
The command any(x) < 0 seems to return False every single time.
How would I have to go about it?
any is not vectorized. You'd have to apply it on each object in x:
any(n < 0 for n in x)
n < 0 for n in x creates a generator that yields one value at a time from x, and is quite efficient since it is short-circuited, meaning it will break (and return True) as soon as it finds the first n that is < 0.
You can also use numpy for vectorized operations
import numpy as np
x = np.array([1.2, -0.4, 3.5,0])
x<=0 # will return the array of boolean values
If you just need to check if the condition met or not then
any(x<=0) # will return true if array contains atleast one True
When using any() or all() the pc will check if the elements in the iterableare True or False. Thus, you need to add a list comprehension to create the iterable:
any([elt < 0 for elt in x])
Basically you need to do the following:
any(value < 0 for value in X)
You can find a detailed explanation here
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
first = int(input('first int: '))
second = int (input('second int: '))
result =0
if first and second:
result =1
elif not first:
result =2
elif first or second:
result=3
else:
result=4
print(result)
when I enter 1 and 0, the result is 3. I would appreciate if anyone could add some explanation.
You are using or- it means the statement will return True when it first finds True.
When you say 5 or 9, both 5 and 9 represent truism (as does any non-zero value). So it returns the first - 5 in this case. When you say 9 or 5, it returns 9.
EDIT: k = 1 or 0 would evaluate to True since 1 represents truism. Thus, as per your code, result is 3
In many program languages, the boolean operations only evaluate their second argument if needed for their outcome. These called short-circuit operator. And in python, according the docs, it returns:
x or y : if x is false, then y, else x
x and y : if x is false, then x, else y