0

I have the following code:

word = ""
if (letter=="a" for letter in word):
    print("a found!")

which prints a found! even though word variable is empty. Why is this happening? And what is the right way to do what I want?

5 Answers 5

2

The condition you used in if returns a generator expression <generator object <genexpr> at 0xefd89660> which is always True. To verify what your condition returns,

print(letter=="a" for letter in word)
# <generator object <genexpr> at 0xefd89660>

Hence you get what you got.

Right way:

word = ""
for x in word:
    if x == 'a':
        print('a found!')

Iterate through word, compare if it equals 'a' and do whatever if condition is satisfied.

Or even better:

if 'a' in word:
    print('a found!')
Sign up to request clarification or add additional context in comments.

Comments

2

That is happening because the statement (letter=="a" for letter in word) is a generator. Your if statement checks if that generator is a "truthy" object (lots of things in python evaluate to true for convenience -- nonempty lists, nonempty strings, etc...) and then prints "a found!" since the generator evaluates to True.

Instead, you probably want something like the following.

word = ""
letter = "a"
if letter in word:
    print(f"{letter} found!")

Comments

0

(letter=="a" for letter in word) returns a generator. Since generators don't seem to have have a __len__ nor a __bool__ it always evaluates as true.

The code you want is this one:

word = ""
if ("a" in word):
  print("a found!")

Comments

0

Actually, you can use

for a in word:....

but if you persis your manner, you should write as follows:

import numpy as np
word = "abc"
if np.any(list(letter=="a" for letter in word)):
    print("a found!")

pull elements out of the generator, and use np.any() to get your result.

Comments

0

Previous answers explain the why it is not working, here is just a way to use list comprehension to solve your problem:

word = "StackOverflow"
[print(letter + " found in:", word) for letter in word if letter == "a"]

Which returns:

a found in: StackOverflow

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.