Home > Mobile >  List resets after for loop
List resets after for loop

Time:12-12

A list is defined at the beginning of a function, then appended to in a for loop, and printed at the end of the function which returns an empty list.

The Code:

def get_chest_tiles(map):
    chest_tiles = []
    y = 0
    for layer in map:
        x = 0
        for tile in layer:
            if tile == -1:
                chest_tiles.append((x * 16, y * 16))
                #print(chest_tiles) #* returns correct list
                chance = random.randint(0, 5)
                if chance >= 0 and chance <= 2:
                    map[y][x] = 18
                elif chance >= 3 and chance <= 4:
                    map[y][x] = 19
                else:
                    map[y][x] = 20
            x  = 1
        y  = 1

    print(chest_tiles) # returns []
    return chest_tiles # returns []

The commented out print statement under the append returns the following:

[(864, 48)]
[(864, 48), (960, 48)]
[(864, 48), (960, 48), (0, 160)]
[(864, 48), (960, 48), (0, 160), (208, 160)]

which is what is expected.

The print and return statements at the end of the for loop both return an empty list. How can I fix this?

CodePudding user response:

Summarising changes from the comments:

def get_chest_tiles(the_map):
    chest_tiles = []
    for y, layer in enumerate(the_map):
        for x, tile in enumerate(layer):
            if tile in (-1, 18, 19, 20):
                chest_tiles.append((x * 16, y * 16))

            if tile == -1:
                chance = random.randint(0, 5)
                if 0 <= chance <= 2:
                    the_map[y][x] = 18
                elif 3 <= chance <= 4:
                    the_map[y][x] = 19
                else:
                    the_map[y][x] = 20

    print(chest_tiles)
    return chest_tiles
  • Related