-1

This is the code I entered

l = input("Enter a list : ")

lst = list(l)

item = int(input("Enter an element : "))
s = len(lst)

for i in range(s):
    if item == list[i]:
        print("Element is in the list")
        break
    elif item != list[i]:
        print("Element is not in the list")
        break

When I enter any element such as a string element it always shows element not found in the list, Here is the code sample of the result

Enter a list : ["Tan", "Ban", "Ran"]
Enter an element : "Tan"
Element is not in the list
cards
  • 3,936
  • 1
  • 7
  • 25
Shivansh
  • 1
  • 1
  • 1
    If you apply `list()` to a string, the *individual characters* of the string become the elements of the list. So the elements of your input `["Tan", "Ban", "Ran"]` are `[`, `"`, `T`, and so on - nothing longer than one character will be present in the list. – jasonharper Mar 16 '22 at 15:48
  • 1
    To format the code - select it and type `ctrl-k`. .. [Formatting help](https://stackoverflow.com/editing-help)... [Formatting sandbox](https://meta.stackexchange.com/questions/3122/formatting-sandbox) – wwii Mar 16 '22 at 16:27

1 Answers1

0

You need to use the in keyword. if item in list: and that should solve the problem. But that is not the only problem. list(l) separates every character entered. So you need to take a string as input and then split it. Correct Code:

l = input("Enter a list(items separated by a space) :") # Entering String
l = l.split() # converting string to List by separating elements
item = (input("Enter an element : ")) # The element won't necessarily be an integer, 
                                      # so take a string input
# Conditional Statements
if item in l: 
    print("Element is in the list")

else:
    print("Element is not in the list")

Sample Output:

Enter a list(items separated by a space) :
Tan Ban Can
Enter an element : 
Tan
Element is in the list

Anshumaan Mishra
  • 1,349
  • 1
  • 4
  • 19