I came across this concept but i couldn't get it
my_list = [False]
string = "a" if my_list else "b"
print(string)
The answer for the above code is a. Please help me to understand it.
Python interprets an empty list as False and a filled list as True. Just like empty and full strings.
An empty list is treated as False while if anything is present inside the list (e.g 0 or False or anything), the list will be treated as true value
string = "a" if my_list else "b"
During the condition checking in if block, as one element is present and it was not empty, the condition got True value and the 'a' came as output.
let's say that the list is empty, then the else part will be an answer.
my_list = []
string = "a" if my_list else "b"
print(string) # prints b
Falsy values in python,
Related
In this problem, I take two strings from the user, the first string being s and the second string being t. If t is the reverse of s, I print "YES" else I print "NO".
Here is my code which gives me expected outputs:
s = input()
t = input()
if t == s[::-1]:
print("YES")
else:
print("NO")
But I found another approach that I am curious to understand, but the slicing part is making me confused. Here the code goes:
print("YNEOS"[input()!=input()[::-1]::2])
Trying to find a good explanation, so StackOverflow is what came to my mind before anything else.
Let's first extract the parts of that expression that concern the input/output and the string reversal. We then get this solution:
s = input()
t = input()
trev = t[::-1]
result = "YNEOS"[s != trev::2]
print(result)
The focus of the question is on the expression "YNEOS"[s != trev::2]
Now we get to the "trick" that is performed here. The expression s != trev can be either False or True. This boolean value becomes the first part in the slicing. You'd expect to have the start index of the slice at this position. But the boolean value will also work, as booleans are a subclass of integers, and False is 0 and True is 1. So the above expression evaluates to either:
"YNEOS"[0::2]
or
"YNEOS"[1::2]
The 2 serves as the step, and so "YNEOS"[0::2] will take the characters at indices 0, 2 and 4 ("YES"), while "YNEOS"[1::2] takes the characters at indices 1 and 3 ("NO").
I hope this clarifies it.
str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
str_list = [x for x in str_list if x]
print(str_list)
Python supports the concepts of "truthy," meaning a value treated as logically true, and "falsey," a value logically treated as false. As it turns out, empty string is falsey, so the if x condition in the list comprehension will exclude empty string values.
Here, checking if x is implicitly looking at bool(x). Specifically, notice that when x is an empty string, bool(x) is false: we say that it is "falsy." You can see this for yourself interactively:
>>> bool("Emma")
True
>>> bool("")
False
>>>
This list comprehension effectively filters out these "falsy" values, or in this case, empty strings.
For more about common truth values and how to customize your own, see the Python docs.
So far, I have:
my_list = ['hello', 'oi']
comparison_list = ['this hellotext', 'this oitext']
for w in my_list:
if w in comparison_list: print('yes')
However, nothing prints because no element in my_list equals any element in comparison_list.
So how do I make this check as a subset or total occurance?
Ideal output:
yes
yes
You are checking the occurrence of the complete string in the list currently. Instead you can check for the occurrence of the string inside each comparison string and make a decision. A simple approach will be to re-write the loop as below
for w in my_list:
# Check for every comparison string. any() considers atleast 1 true value
if any([True for word in comparison_list if w in word]):
print('yes')
It's because you're comparing w to the list elements. If you wanna find w in each string in your comparison_list you can use any:
my_list = ['hello', 'oi', 'abcde']
comparison_list = ['this hellotext', 'this oitext']
for w in my_list:
if any(w in s for s in comparison_list):
print('yes')
else:
print('no')
I added a string to your list and handle the 'no' case in order to get an output for each element
Output:
yes
yes
no
Edited Solution:
Apologies for older solution, I was confused somehow.
Using re module , we can use re.search to determine if the string is present in the list of items. To do this we can create an expression using str.join to concatenate all the strings using |. Once the expression is created we can iterate through the list of comparison to be done. Note | means 'Or', so any of the searched strings if present should return bool value of True. Note I am assuming there are no special characters present in the my_list.
import re
reg = '|'.join(my_list)
for item in comparison_list:
print(bool(re.search(reg, item)))
I've written some code and here's a short bit
x = ['apple, iphone','samsung, galaxy','oneplus, 10pro']
print('apple' in x)
how do I get this statement as true, since apple already exists in x, I still keep getting the False as the boolean value.
When the in operator is applied to a list like you have here it looks for an exact match in the list. Your code is returning false because 'apple' isn't in the list, 'apple, iphone' is. To check each element in the list for the substring 'apple' you could use list comprehension. Something like:
x = ['apple, iphone','samsung, galaxy','oneplus, 10pro']
print(True in ['apple' in s for s in x])
What the second line does is use list comprehension to build a list of booleans indicating if the substring 'apple' is in that element. Then it checks if True is in the resulting list.
or instead of using the in operator:
x = ['apple, iphone','samsung, galaxy','oneplus, 10pro']
print(any(['apple' in s for s in x]))
The any built-in function returns true if any element in an iterable is True.
x = ['apple, iphone','samsung, galaxy','oneplus, 10pro']
print(True in ('apple' in d for d in x))
Maybe use a function like this:
IsItemInList(item, list):
for x in list:
if x == item:
return True
return False
Pretty sure theres a much cleaner way to do this but that was my first guess. As we know, the first is mostly the worst.
I just started to use python 3. I want to find specific characters inside a string that is part of a list. Here is my code:
num = ["one","two","threex"]
for item in num:
if item.find("x"):
print("found")
So, I want to print "found" if the character "x" is inside of one of the elements of the list. But when I run the code, it prints 3 times instead of one.
Why is printing 3 times? Can someone help me?
find() returns -1 if the character is not found in the string. Anything that is not zero is equal to True. try if item.find("x") > -1.
You can use in again for strings:
num = ["one","two","threex"]
for item in num:
if "x" in item:
print("found")
Think in Strings as a list of chars like "ext" -> ['e', 'x', 't']
so "x" in "extreme" is True
find returns Index if found and -1 otherwise.
num = ["one","two","threex"]
for item in num:
if item.find("x"):
print item.find("x")
i hope that you got the solution from above post ,here you know the reason why
You need to break out of looping through the strings if 'x' is found as otherwise, it may be found in other strings. Also, when checking if 'x' is in the string, use in instead.
num = ["one","two","threex"]
for item in num:
if "x" in item:
print("found")
break
which outputs:
found
And if I modify the num list so that it has no x in any of the elements:
num = ["one","two","three"]
then there is no output when running the code again.
But why was it printing 3 times before?
Well simply, using item.find("x") will return an integer of the index of 'x' in the string. And the problem with evaluating this with an if-statement is that an integer always evaluates to True unless it is 0. This means that every string in the num list passed the test: if item.find("x") and so for each of the 3 strings, found was printed. In fact, the only time that found wouldn't be printed would be if the string began with an 'x'. In which case, the index of 'x' would be 0 and the if would evaluate to False.
Hope this clears up why your code wasn't working.
Oh, and some examples of testing the if:
>>> if 0:
... print("yes")
...
>>> if 1:
... print("yes")
...
yes
>>> if -1:
... print("yes")
...
yes