You can simply loop over a sorted list (first by the state, then by name):

city_list = [('Huntsville', 'AL'), ('Decatur', 'AL'), ('Anchorage', 'NV'), 
('Nome', 'AK'),('Selma', 'AL'), ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), 
('Tucson', 'AZ')]
sorted_list = sorted(city_list, key=lambda x: (x[1],[0]))

last = None
for city, state in sorted_list:
    if state != last:
        print(state)
        last = state
    print(city)

Reply via email to