Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – list resets after for loop

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[(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 statement at the end of the for loop both return an empty list. How can I fix this?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading