I am a beginner in programming and I am trying to implement if...else statement but being failed. I have an array list and I have to check it does not contain a specific value. But the else statement does not work.
#For an example:
a=[10,12.0,13.0]
b=[12.0]
if a <= b:
print("something")
else:
print("others") #else statement doesn't work
I think what you're looking for is an iteration. Currently you're asking if your list a is less than or equal to your list b, but semantically this doesn't have a lot of meaning. In fact, Python seems to somewhat unintuitively select the first element of each list in order to perform the comparison. Thus, in the example code you give it will always evaluate as True since 10 < 12.0.
However, if you add an iterator like so:
a=[10,12.0,13.0]
b=[12.0]
for ai in a:
for bi in b:
if ai <= bi:
print(f"a={ai} b={bi} and a is strictly smaller.")
else:
print(f"a={ai} b={bi} and a is equal or greater.")
In this manner you can compare every item in a with every item in b.
However, if you simply want to ensure that 12.0 is not in a, Python provides a much simpler way:
a=[10,12.0,13.0]
b=[12.0]
if b[0] in a:
print("The list contains the selected value.")
Related
This question already has answers here:
Check if something is (not) in a list in Python
(4 answers)
Closed 1 year ago.
I have a list: list = ['abd','def','gab','dab']
And I want to check if a certain element say x = 'gab' is equal to an element in the list.
If so, then I want to do something, otherwise I want to pass. And at the end of the for loop, if x was not equal to any element in list, then I want to run some batch of code.
Here is my code:
for string in range(len(list)):
if list(string) ==x:
do something...
break
else:
pass
The challenge I have is to write the condition to check if x is not equal to any element in list- how can I write this condition?
Intuitively, I would write this code after the for loop- but the issue is that it will then execute regardless of whether x is equal to an element in list or not, and I don't want this, as I only want this next block of code to execute if x was not equal to an element in list! I hope this makes sense.
In this case, you can use: if x in list:
In more complex situations, if you have something more complex than a simple comparison, you could do: if any(x == item for item in list):
As a side note, it's not a good idea to use the name list, because Python already uses that name and it could get confusing.
PS: To add another solution, in Python a for loop can have an else clause, which is executed if there was no break; that will be useful if the body of the loop is too complex to fit into a single expression.
You can use any()
x = 'gab'
list1 = ['abd','def','gab','dab']
if any(x==item for item in list1):
print("Yes. Match found.")
else:
print("Match was not found")
Every now and then I fall on this pattern when looping through an array:
for a in b:
if a==y:
#do somethinng
return 1
there is no else statement because I need to check the full array for a==y (let's say a is name in a dir list) before returning anything.
It would also be a good idea to return something only if no element in the array fulfills the condition a==y
How should I re organize the code in this sense?
How do I tell the caller if the loop doesn't 'succeed' in finding 'y'?
If you are expecting to encounter y only once or only take into account its first occurrence (given that you have a return statement within the condition), then here's another method:
if any(a == y for a in b):
#do something
return 1
else:
return 0
It would probably be a good idea to return something only if no element in the array fulfills the condition x==b but I don't know how to re organize the code in this sense.
The usual thing is to put the return reflecting the fact that nothing matched after the loop:
for a in b:
if a==y:
#do somethinng
return 1
return 0 # or whatever
In some cases, it may be appropriate to throw an exception after the loop instead, if the fact that nothing matched within the loop is an exceptional condition, not a normal case.
Please be sure to check out navneethc's answer using any as well.
My code in Python reads a next element in list and checks whether it already appeared in the list before. If yes, then it moves a left bound of the list behind the previous appearance (the rest of the code does not matter):
while k<len(lst):
if lst[k] in lst[a:k]: #a is a left bound
i = lst.index(lst[k],a) #could be done more effeciently with exception handling
a = i+1
k += 1
I tried to rewrite this without using high-level tricks (in/index):
while k<len(lst):
for i in range(a,k+1):
if lst[i] == lst[k]:
break
if i != k: #different indices, same values
a = i+1
k += 1
This appears to be cca 3.5 times slower than the code #1. But I do not think the code #2 does something highly inefficient, if I understand the "in" command correctly.
go through all elements in list
compare to the searched element
if they are equal, stop and return True
if at end of the list, return False
(and the function index probably works in the same way, you only have to remember also the index).
My guess is that the Python interpreter interprets the "in" as a low-level version of the for-cycle in code #2. But in the code #2, it has to interpret my comparison every time I increase the value of i, which makes the code run slowly overall. Am I right about this?
By the way, the list is an ordered list of non-repeating numbers (does not have to be, so no suggestions of binary search), which results in a worst-case complexity for this algorithm, n^2/2.
I have this question and I want your expert answers about it, because I want to get better in programming.
"""
The parameter s_str is a string. The parameter n is an int > 0.
The function x() should return the last n characters of s_str if
s_str has a length >= n, or the empty string if s_str has a length < n
Example:
x('abcdef', 3) == 'def'
"""
So, I could build the exact code with or without the for statement and it would give me (print) the same values, but I don't know what is the more common way to do it. If I'd go for a for statement, I'd do this:
for i in s_str:
if len(s_str) >= n:
return a_str[-n:]
elif len(s_str) < n:
return ''
Is the idea of using a for statement wrong if you know in advance that you are not going to use i, in this case? I could easily remove the for statement and still get the right answer, so is that enough reason not to use it?
There are cases in which a for loop is justified even if you do not intend to use the loop index (e.g when you want to preform a certain task n times). Having said that, this problem can be solved in a more elegant way, as you have shown.
Also please note that your code iterates over the string len(str) times, except it returns in the first iteration, so the for loop in this case is redundant.
"so is that enough reason not to use it?"
Yes. Simple is better than complex.
You dont actually need a for loop
if len(a_str) >= n:
return a_str[-n:]
it is better and simple too.
Please keep in mind that I am still fairly new to Python. I have this question which I have a fair bit of trouble understanding. I have made an attempt at this problem:
def Sample(A):
for i in range(len(A)):
if A == 1:
print A
elif A == (-1):
print A
Question:
Write a function where A is a list of strings, as of such print all the strings in A that start with '-1' or '1'
In your if and elif you are testing A, i.e. whether the whole list is equal to the value, which will never be True. Instead, test, each item in A. You can either stick with your index:
for i in range(len(A)):
if A[i] == ...
or, better, iterate over A directly:
for item in A:
if item == ...
Next, to test whether a string starts with a character, use str.startswith:
for item in A:
if item.startswith("1"):
...
Note that this uses the string "1", rather than the integer 1.
You're comparing if A equals 1 or -1, which is a bad start. You should be checking if i starts with either of those.
if i.startwith("1"):
Edit:
I completely edited my answer since I had misunderstood the question the first time.
You need to test for two cases does a_string in A start with '1' or start with -1.
Python offers a number ways to do this. First, is the string.startswith('something') method. This checks to see if the string startswith something you specified.
def Sample(A):
for each_string in A:
if each_string.startswith(('1','-1')):
print each_string