How Can You Search For An Item In A List - Python
This is probably a very simple program but I tried to find an item in a list (in python) and it just doesn't seem to work. I made a simple list called Names and had variables: fou
Solution 1:
you can use the in operator simply to check if one element exists or not.
item in my_list
Solution 2:
This is one of the simplest ways to find the index of an item in a list. I'll use an example to explain this. Suppose we have a list of fruits(List_Of_Fruits) and we need to find the index of a fruit(Fruit_To_Search),we can use the given code.
The main part is the function index() its syntax is list.index(item) this will give the index of 'item' in 'list'
#A list with a bunch ofitems(inthiscase fruits)
List_Of_Fruits = ["Apples" , "Bananas" , "Cherries" , "Melons"]
#Getting an input from the user
Fruit_To_Search = input()
#You can use 'in' to check if something is in a list or string
ifFruit_To_Search inList_Of_Fruits:
#If the fruit to find is in the list,
Fruit_Index = List_Of_Fruits.index(Fruit_To_Search)
#List_Of_Fruits.index(Fruit_to_Search) gives the index of the variable Fruit_to_Search in the list List_Of_Fruits
print(Fruit_To_Search,"exists in the list. Its index is - ",Fruit_Index)
else:
print(Fruit_To_Search,"does not exist in the list"
Solution 3:
Generally to check if an item is in a list you could as Python to check for that. But this would be case-sensitive. Otherwise you would have to lowercase the list first.
names = ['Mike', 'John', 'Terry']
if'Mike'in names:
print ("Found")
else:
print ("Not Found")
Solution 4:
You can use the in
operator to search elements in a list. it will return True
if that element is present in the list else False
.
if Searchname in Names:
found=Trueprint('Found')
else:
print('Not found')
Post a Comment for "How Can You Search For An Item In A List - Python"