Loop for Nested list not working correctly?

I’m working through Python 3, finished the lists and almost through the loops but not understanding looping for nested lists. I’ve searched and read post after post but still not getting it.

I have a list with sample employees and the department they work in. The user inputs who they are looking for, it should print the names but it only prints the name in the first nested list. The user input is entered and it only finds the first user and department, but then it prints the second user. It will not find the second user but it prints it. Any instruction on what I’m doing wrong would be appreciated. If there is other resources you know of on this subject please let me know. Thanks!

list1 = [["mike","plumber"],["matt","electrician"]]

print("Who are you looking for?")
for x in list1:
  print(x[0])
  lookup = input("Enter name ")

  for i in list1:
    if lookup in i:
      print("Found user: " + i[0])
      print("Occupation is: " + i[1])
      break
    else:
      print("No user found.")
      break

Output below

Who are you looking for?
mike
Enter name mike
Found user: mike
Occupation is: plumber
matt
Enter name matt
No user found.

1 Like

Both your loops iterate through the same list
For the second user perhaps you mean to start over from the same state as when the search for the first user took place?

def search(firstname):
    ... do something
    return some result found/nothing

while True:
    get query from user
    search(firstname)
    report result
1 Like

Looks like you’ll need to do some refactoring. In addition to using two loops to iterate over the same list as @ionatan pointed out, you’ve limited your nested loop to only checking the first element. Take a look at your if ... else In the first iteration of your for i in list1: loop, you check if lookup is in i. Then you break out of the loop whether it is or isn’t, so the subsequent elements of your list1 are never checked.

1 Like

Thanks I’ll take a look at it see if I can figure it out!

Thanks for the example I’ll see what I can do!