Python Forum
How do I understand "and" in a loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I understand "and" in a loop
#1
Hi,

I'm trying to get a better understanding for "and" in a loop. For the script below, I'm trying to get index 1, but it returns index 1 and 2.

b = ["abc", "bcd","cde"]

for i in range(len(b)):
    if "b" and "d" in b[i]:
        print (i)



if I change it like this, and expected no returns (cause none item in b has "bc" and "cd" at the same time), it actually gives me index 1 and 2 again.

b = ["abc", "bcd","cde"]

for i in range(len(b)):
    if "bc" and "cd" in b[i]:
        print (i)
Can someone help? Thanks!
Reply
#2
"and" isn't special in a loop. You're probably getting confused by precedence. and has fairly low precedence, lower than in. So the expression in your first example should be parsed this way:

if ("b") and ("d" in b[i]):
"b" is always true, so the branch is taken whenever "d" is found in b[i], which is the indexes you describe. Your second example is similar.

if ("bc") and ("cd" in b[i]):
True whenever "cd" is in b[i], which is correct for index 1 and 2.

You probably want something similar to this:
if "b" in b[i] and "d" in b[i]:
or

if all(x in b[i] for x in "bd"):
Reply
#3
Thanks a lot!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [ESP32 Micropython]Total noob here, I don't understand why this while loop won't run. wh33t 9 1,741 Feb-28-2023, 07:00 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020