Python - Nested for loops

Introduction

The next example illustrates statement nesting and the loop else clause in a for.

Given a list of objects (items) and a list of keys (tests), this code searches for each key in the objects list and reports on the search's outcome:

Demo

items = ["aaa", 111, (4, 5), 2.01]      # A set of objects 
tests = [(4, 5), 3.14]                  # Keys to search for 
#   w ww  .  j a v a2 s  .  co  m
for key in tests:                       # For all keys 
    for item in items:                  # For all items 
        if item == key:                 # Check for match 
            print(key, "was found") 
            break 
    else: 
        print(key, "not found!")

Result

Related Topic