Home > Net >  python facing problems writing for loop logic when I have multiple items in my list
python facing problems writing for loop logic when I have multiple items in my list

Time:05-12

My for loop working when I have only one item in my list. see the code below:

remove_month_year = ["apple","banana"]   
for remove_m_y in remove_month_year:
    if remove_m_y not in time_posted: #I want to exceute this line of code if "apple" and "banna" not found in time_posted
       ....my others code

#time_posted is list of string like time_posted = "he eat apple" 

But when I added more then one item I am facing the problems. Let you explain: Assume I have two item in my list ["apple","banana"] so when I running the for loop first it will check for "apple" if apple not found then it will run my others block of code which is okay. The problems occurs when it's checking banana and found apple and my others block code running where I added logic not to run code if found apple.

CodePudding user response:

It’s iterating over the array with one variable at a time, so imo you could either add a Boolean value which is changed upon one being present, followed by a conditional after the loop to check that Boolean value, or a more efficient way would be


remove_month_year = ["apple","banana"]   
if(not any(remove_m_y in time_posted for remove_m_y in remove_month_year)):
       ....my others code

#time_posted is list of string like time_posted = "he eat apple" 

Not sure if this exactly will work, but I think it should…

any returns true if any element is true, and false if all are, so this is probably perfect

  • Related