简体   繁体   中英

Why am I getting an UnboundLocalError even though I am just defining a variable?

def alphabet_war(airstrikes):
    bombs = []
    for i in range(len(airstrikes)):
        bombs.append([])

    for bomb in airstrikes:
        bomb_index = index(bomb)
        for index in range(len(bomb)):
            if bomb[index] == "*":
                bombs[bomb_index].append(index)

    return bombs

I am getting a "UnboundLocalError: local variable 'index' referenced before assignment" for line bomb_index = index(bomb) .

While I have seen many articles on this, including: https://careerkarma.com/blog/python-local-variable-referenced-before-assignment/ that is quite helpful.

I am still struggling to understand why I am getting this error. I don't see how I am using it before assigning it locally? I thought all I am doing is defining bomb_index

I have also tried changing it slightly to the more concise:

for bomb in airstrikes:
    for index in range(len(bomb)):
        if bomb[index] == "*":
            bombs[index(bomb)].append(index)

But here for index(bomb) I get a int object not callable error

The issue is bomb_index = index(bomb) , index is not a defined name at that point of your code.

Presumably, what you want is to know what index bomb has in airstrikes . The wrong way to do this (still using list.index() as you originally intended) is:

bomb_index = airstrikes.index(bomb) # scans airstrikes at every iteration searching for bomb

The right way to do this is to enumerate the items in the list as you loop over them:

for bomb_index, bomb in enumerate(airstrikes): # no need for searching, you loop and know the index of every item as you loop over them
    for index in range(len(bomb)):
        if bomb[index] == "*":
            bombs[bomb_index].append(index)

In the line:

bomb_index = index(bomb)

index is undefined, because its firstly declared by the for loop directly below it. I think what you're trying to do here is loop trough list values and indices simultaneously. For this, you can use enumerate :

lst = ['a', 'b', 'c']

for index, value in enumerate(lst):
    print(index, value)
    
#  Returns:
#  0 a
#  1 b
#  2 c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM