-1

If value like element in list then print that element in list.

val = 'https://www.google.com/search?q=google'

elements = ['google.com', 'bing.com', 'yahoo.com']

I want the result google.com.

My code:

if val in elements:
    print(elements)

I know print(elements) will print all the elements in the list. But can I just print the one element it matches to?

I want to do val like in elements print the element it matches to

4
  • You can iterate over elements and do if val in element: ...
    – zamir
    Jan 14, 2020 at 16:49
  • @zamir, I did that and it didnt return any thing
    – nb_nb_nb
    Jan 14, 2020 at 16:50
  • What is if val in elements ? It will always return None
    – Mukesh Jha
    Jan 14, 2020 at 16:51
  • 1
    You're doing the opposite validation. The <em>Element</em> is in the value, not the other way around. Try searching each element in your value, instead. Jan 14, 2020 at 16:52

2 Answers 2

4

Try this.

for el in elements:
    if el in val:
        print(el)
0

You have the for loop backwards in your step above. Since the value in elements are the subsection of val you need to iterate through elements are check if it is in val.

for i in elements:
    if i in val:
    print(i)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.