Python For Else Loop

Python

An example of using a For Else loop.

In this code snippet a For loop iterates through a list of city names and checks if any match the string in the new_city variable. If the loop is exhausted then this triggers the else clause.

 1|  cities = ['London','New York','Paris']
 2|  new_city = 'Madrid'
 3|  
 4|  for city in cities:
 5|      if new_city == city:
 6|          print('City in list')
 7|          break
 8|  else:
 9|      print('City not in list')
Did you find this snippet useful?

Sign up for free to to add this to your code library