-1

I have a list containing strings

 list=["geeks for geeks","string1","string2","geeks"]

I want to check if "geek" is present in the list, if present fetch me the whole string from the list

if geek in list:

output :
    geeks for geeks
    geeks

how to achieve this?

Guy
  • 46,488
  • 10
  • 44
  • 88
harshith
  • 71
  • 9
  • you have asked many questions over your time on Stack Overflow, but have not accepted any answers. If you feel one of the answers to this question (or others) has answered your question, it is good etiquette to accept the answer. – Chris Aug 14 '22 at 00:33

2 Answers2

0

Please replace the Python reserved word list with another variable name like lis or words. You can try this

lis = ["geeks for geeks", "string1", "string2", "geeks"]
for word in lis:
    if "geek" in word:
        print(word)

The output is

geeks for geeks
geeks

Or if you want to append to a new list

words = []
for word in lis:
    if "geek" in word:
        words.append(word)
print(words)

Or using list comprehension (thanks @Chris!)

[word for word in lis if "geek" in word]

The output is a list

['geeks for geeks', 'geeks']
MiH
  • 354
  • 4
  • 11
  • 1
    You may wish to properly name that "1-liner" as a "list comprehension" so that the OP can know what to research. – Chris Aug 12 '22 at 07:36
  • thanks @Chris.. you're a "Copy Editor" (gold badge) so you could have edited my answer also, why did you stop doing so after 500? haha i'm just curious – MiH Aug 12 '22 at 13:10
  • I didn't. I've edited 1,269 posts. So far. – Chris Aug 14 '22 at 06:08
0

Sounds like you want a list comprehension.

lst = ["geeks for geeks", "string1", "string2", "geeks"]
lst2 = [s for s in lst if "geek" in s]
# ['geeks for geeks', 'geeks']

You may wish to use str.lower to account for different capitalizations of "geek".

lst2 = [s for s in lst if "geek" in s.lower()]
Chris
  • 26,361
  • 5
  • 21
  • 42