Python program to search a given string from the list of strings using loop

 Python Program to search a given string from the list of strings using loop

In this example, we will learn to search a string in a list of strings using loop.
Logic behind the program is explained below in detail.



Logic 

As we have to search the string using loop, we will iterate through all the elements of the list one by one and then will check whether the elements through which we are iterating anywhere matches the string which we have to find.

Consider a list L containing some strings

L = ["Hello","Sir","Subscribe","Like","Share","Welcome","Thanks"]

Now, we will take input the string to be searched in the list by the user.

esearch = input("Enter element to be searched")

Now, let's create a found variables which will get true when the element matches the string entered by the user. Initial value of found is set to be false.

found = False

To iterate through all the elements of the list we will use for loop.

for element in L:

At every run of code in the loop, the element variable we will have the values of the strings in the list. When it matches the string entered by the user we will set found variable to true.

    if element == esearch:
        found = True

Then we will give a final message according to the value of found variable. If it's value is true then we will print that the element in present in list otherwise we will print element is not present in the list.

if found == True:
    print(esearch, "is present in list")
else:
    print(esearch, "is not present in list")

I hope the logic for question would be clear to you.

You can run and code in python online on this website - Python Online Interpreter

Complete source code the program is given below:-

Source Code

L = ["Hello","Sir","Subscribe","Like","Share","Welcome","Thanks"]
esearch = input("Enter element to be searched ")
found = False

#Looping through each element of list
for element in L:
    if element == esearch:
        found = True

if found == True:
    print(esearch, "is present in list")
else:
    print(esearch, "is not present in list")
Output

Enter element to be searched Like
Like is present in list
Enter element to be searched Bye
Bye is not present in list

If you like the content, share it in your social media platforms so that we can help the maximum. If you have any query then feel free to ask in the comments below.
We are ready to help you.

Check Similar Programs Here - Python Programs - Question and Answers

Enjoy Coding!!

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment (0)

Previous Post Next Post