0

I have a single element list like below

listx=['Digital Operations']

My goal is to just check if the word 'Digital' is present in the list listx

I wrote the below code

if any('Digital') in listx:
  print("the word digital is present")
else:
  print("word Digital not found")

I am getting the output "word Digital not found" despite it being clearly there. What am i doing wrong?

user10083444
  • 105
  • 1
  • 1
  • 10
  • just `if in` for you `if 'Digital' in listx` – Brown Bear May 04 '20 at 18:40
  • 1
    @BearBrown No, `'Digital'` is not in `listx`, it's in *an element* of `listx`, so you need to loop over `listx` – wjandrea May 04 '20 at 18:55
  • @wjandrea thank you. Hope the down vote is removed if no other duplicates are found. – user10083444 May 04 '20 at 19:07
  • Duplicate: [Check if a Python list item contains a string inside another string](https://stackoverflow.com/q/4843158/4518341) – wjandrea May 04 '20 at 19:11
  • @wjandrea my question was about single element list, the link provides a case of multiple elements in a list. I believe there is a subtle difference and hence not duplicate. Anyways I am ok if you deem it as duplicate. – user10083444 May 04 '20 at 19:21

3 Answers3

2

Try this:-

listx=['Digital Operations']

if 'Digital' in listx[0]:
    print("the word digital is present")
else:
    print("word Digital not found")

Output:-

the word digital is present
Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17
2

the any() function takes an iterable (for example a list) and returns True if any of its values is True. You are calling it with a str wich will evaluate to True So basically your if statement then says

if True in listx:

which will in turn evaluate to False, causing your problem.

If you would like to use any() you could use a list comprehension like this:

listx = ['Digital Operations']

listy = ['Digital' in elem for elem in listx]
if any(listy):
  print("the word digital is present")
else:
  print("word Digital not found")

For a more efficent version you can use a generator expression that replaces the need for listy and combines it into the if-statement like this:

if any('Digital' in elem for elem in listx):

thank's to wjandrea comment

bckmnn
  • 64
  • 4
  • 2
    You can make this more efficient by using a generator expression instead of a list: `any('Digital' in elem for elem in listx)`. Though for a single element list it doesn't make a difference. – wjandrea May 04 '20 at 19:06
1

any() checks for True values, so if you change your first line to

if any(any([x=='Digital' for x in y.split()]) for y in listx):

You should be fine.

Igor Rivin
  • 4,632
  • 2
  • 23
  • 35