if statement with square bracket [duplicate] - python

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 2 years ago.
I would like to know what if the difference with and without square bracket
Here is my code without square bracket in the if statement, which answer is correct.
a=[3,90,3,7,8,100]
if sum(a)<100:
a.append(2)
print(a)
While if I put the square bracket, it will be wrong, Can anyone explain it to me?
a=[3,90,3,7,8,100]
if [sum(a)<100]:
a.append(2)
print(a)

So when you use the square brakets, python check whether the list is empty rather then the value inside the list.
This is always interpreted as True, thus the wrong results.
Example to emphasize it:
l = [True]
if l:
print("test")
l = [False]
if l:
print("test")
Both cases will print "test".

a=[3,90,3,7,8,100] # in python lists are denoted by square brackets
if sum(a)<100: # Here sum(a) means sum([3,90,...]) it's a list and it can add all.
a.append(2) # append means adding new element at end of the list a
print(a)
a=[3,90,3,7,8,100]
if [sum(a)<100]: # here the condition will be always true because [True] is not empty
a.append(2)
print(a)

The check is if the list is empty. See the below for explanation
>>> [sum(a)<100]
[False]
>>> if [False]:
... print('hello')
...
hello
>>> if []:
... print('hello')
...
>>>

if [sum(a)<100]: can be understand as: if [False]:. And [False] will be interpreted as True in if statement (see this). So if statement will be execute.

Related

Disjunction and membership in python [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed last year.
When I try this code:
a = ['b']
if 'i' or 'j' in a:
print('Yes!')
else:
print('No!')
The output is 'Yes!'. Flake8 and python do not complain about an error or bad form.
What exactly happens when the code runs? Why does 'i' or 'j' in a evaluate as true?
The problem is that in the statement i evaluates to True, which means that the statement is then: True or 'j' in a. This is always true and your result will be always 'Yes!'.
You can use something like this to check if one of the values is in your list:
a = ['b']
chars_to_check = ['i', 'j']
filtered_list = [i for i in a if i in chars_to_check]
if len(filtered_list)>0:
print('Yes!')
else:
print('No!')
The example is from this question, where people also posted more efficient or shorter solutions to your problem. The solution I like the most would be this one:
a = ['b']
if {'i','j'} & set(a):
print('Yes!')
else:
print('No!')
EDIT: I think now I understand the question.
First of all python sees that you have a or in your if statement. This means the first expression (in your case 'i') is evaluated first. If the first expression is True, the whole statement is True and the second expression is not even evaluated. The evaluation order of or is explained here for example.
Now to why the first expression is always True. Python automatically evaluates all objects not only boolean values. For this the objects can for example contain a function __bool__() that gives back the boolean value of an object. The object in your case is a single character 'i', which evaluates to True. The reason is that it is defined that the boolean value of a string is always True except for the empty string (''). Here you can see an example of the evaluation:
print(bool('i')) # True
print(bool('')) # False
An answer that shows which objects are considered False and which are considered True can you find here.

if decision with list variable [duplicate]

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 3 years ago.
In C/C++, true is standardized as 1, and false as 0. Although not a good practice,
if variable:
#do something
kind of decision making seems ok in python and it seems makes decision based on whether variable is None or is zero - if it is a number. Followings are reasonable.
a = 123123
if a:
print "if condition is true" # this prints
a = "a string"
if a:
print "if condition is true" # this prints
a = None
if a:
print "if condition is true" # this does not print
However, I wonder why it evaluates to false with an empty list, which is neither None, nor zero. What is the exact implementation of python if statement?
a = [] # a is not None
if a:
print "true" # this does not print
An if statement requires a bool. That means the the expression following the if is analyzed is a boolean context. Said differently it is converted to bool.
If a bool context, the following items evaluate to False (non exhaustive list):
None
numeric 0
empty list
empty string
empty dict
Non null numerics and non empty iterables eveluate to True
Lists are empty, so they're False, that's how python reacts, to know whether something is False so doesn't go trough, do:
>>> bool([])
False
>>>
So it is False.

List comprehension syntax - how to use ... if... else? [duplicate]

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."

Python: removing an item from a list in the if statement condition? [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 4 years ago.
I have this code:
myList = [1, 2, 3, 4, 5]
if (myList.remove(4)):
print "We removed 4, so this is true!"
print myList
When I run it, this is what I get:
[1, 2, 3, 5]
So it appears that the "4" was removed from the list as specified in the condition of the if statement, yet the if statement did not end up being "True" since the print statement did not print to the console. Why is it that the if statement is false?
myList.remove(4) does not return True or False depending on whether the remove operation was successful or not.
Instead, it returns nothing (i.e. None) if successful and raises a ValueError otherwise.
Thus,
if mylist.remove(4):
translates to
if None:
which is False
From the docs:
list.remove(x)
Remove the first item from the list whose value is equal to x. It is an error if there is no such item.
So .remove() either returns None or raises a ValueError, hence it equates to False in your code. Here is a link to the relevant docs for further reading.
The remove function doesn't actually return anything. So, the if statement if checking for a value, doesn't get one, which means the if statement results in a false.
myList = [1, 2, 3, 4, 5]
var1 = myList[3]
if var1:
print "1 - Got a true expression value"
print var1
var2 = myList.remove(4) # Nothing returned (var2 = None)
if var2: # if statement fails because var2 is None
print "2 - Got a true expression value"
print var2
print myList
This will result in the following when the code is executed
1 - Got a true expression value
4
[1,2,3,5]
Because .remove, like del, it doesn't return anything. So, it implicitly returns None, which is evaluates to False in a Boolean expression.
The .remove method for lists returns None when the item was found, and throws an error if not.
Here is one option:
a=[1,2,3,4]
try:
a.remove(4)
print "we removed 4, so this is true!"
except:
pass
print(a)

Behaviour of Python all() operator [duplicate]

This question already has answers here:
Python "all" function with conditional generator expression returning True. Why?
(2 answers)
Closed 9 years ago.
have a question on all() operator in Python.
say
array = ["one","one","one"]
all( x=="one" for x in array ) <<--- i want to check for all "one" in array
The above seem to work. however, if i have
array = []
all( x=="one" for x in array ) <<--- this still return true to me.
The behaviour is that i want it return false if all items are not "one". How to do it? thanks
You can read all() as if it means:
It returns False if any of the items evaluates to False. True otherwise.
So an empty set will return True, because there is none that will make it false.
Generally speaking, in an empty set, all the elements fullfill any requirement you can imagine. That's a principle of logic, not of Python, BTW.
all's implementation is equivalent to this
def all(iterable):
for element in iterable:
if not element:
return False
return True
So, it returns True till any of the elements in the iterable is Falsy. In your case that didnt happen. Thats why it returns True
all always returns True for an empty list/tuple/etc. This is because, technically, every item in an empty collection fulfills any and every condition there is.
To fix the problem, you need to add some additional code to test whether your list is empty or not. Fortunately, empty lists evaluate to False in Python, so you can just do this:
>>> array = []
>>> bool(array and all(x=="one" for x in array))
False
>>> if array and all(x=="one" for x in array):
... print True
... else:
... print False
...
False
>>>
How to do it?
array and all(x=="one" for x in array)
Empty lists are false, so the result is false and it doesn't matter that the all part is true.
If you want to deal with iterables other than containers like list then it's a bit harder. I suppose you need something like this:
set(x=="one" for x in iterable) == { True }
Although if you care about speed, the following should be faster on the whole, since the version above doesn't short-circuit like all does:
def nonempty_all(iterable):
iterator = iter(iterable)
try:
if not next(iterator):
return False
except StopIteration:
return False
return all(iterator)

Categories

Resources