Reputation: 11
I am doing a school project about a inventory system, and I am facing some problem in programming the Search
function.
Take an example:
ilist = [ [1,2,3,4,5], [6,7,8,9,10], [...], ...]
I would like to search for 1
and want the list containing 1
to display.
search = input('By user:')
for item in ilist:
if item == search :
print(item)
It does not work this way and I get this error:
list index out of range error
Upvotes: 0
Views: 118
Reputation: 4562
You can use in
to find the element from each list
search = int(input('By user:'))
for item in ilist:
if search in item:
print(item)
Upvotes: 0
Reputation: 1966
you have a nested list and are now checking against the list ('1' wont match with [1,2,3,4,5] )
so you have to loop over the list within the list and change input to int:
ilist = [ [1,2,3,4,5], [6,7,8,9,10]]
search = input('By user:')
for item in ilist:
for i in item:
if i == int(search):
print(i)
this is building on your way of coding, could be further improved from this
Upvotes: 3
Reputation: 6206
Two problems:
ilist
is a list of lists, and you're comparing search
to each listint
, while search
is of type str
In short, change this:
if item == search
To this:
if int(search) in item
Upvotes: 2