DEV Community

Discussion on: Understanding loops

Collapse
 
waylonwalker profile image
Waylon Walker

You can also get the index in a more pythonic fashion by using the enumerate function to get the index while looping. This version, uses enumerate and f-strings.

# Un-nested for loops

def print_letters_from_countries(countries):
    for i, country in enumerate(countries): #iterate over countries list
        print('beginning of outer loop') 
        print(f'{country} is at index {i} of {countries}\n')
        print(f'beginning of inner loop for {country}')
        print_letters_from_country(country)

def print_letters_from_country(country):
    for i, letter in enumerate(country): #iterate over each country in countries list
        print(f'{letter} is at index {i} of {country}')
    print(f'end of inner loop for {country}\n')


countries = ['Germany','USA','Spain']
print_letters_from_countries(countries)
Collapse
 
jamesbright profile image
James Ononiwu

nice update!