0

I'm having difficulty changing the value of a list of lists. I can't figure out why

I am building a function that creates a tower of stars (looks like a christmas tree)

def tower_builder(n_floors):
    tower = []
    real_tower = []
    block_len = 1 + (2 * (n_floors-1))
    tower_block = []
    center_star = int(block_len / 2)
    n = 0

    #Creates a list of the top block of the tower with a star at the center and spaces for all other list values
    for i in range(block_len):
        if i == center_star:
            tower_block.append("*")
        else:
            tower_block.append(" ")

    #Replicates the top block for other blocks and will change subsequent blocks to have stars in the proper list indexes
    for n in range(n_floors):
        start_index = 0
        end_index = 0
        star_len = 0
        start_index = center_star - n
        end_index = center_star + n
        star_len = (end_index - start_index) + 1
        tower.append(tower_block)
    tower[0][0] = 3
    return(tower)

For some reason, after

tower[0][0] = 3

Instead of modifying the first entry in the first list, it is modifying the first entry in all the lists.

tower_builder(3)
>>>> [[3, ' ', '*', ' ', ' '], [3, ' ', '*', ' ', ' '], [3, ' ', '*', ' ', ' ']]

where I would expect it to return:

    tower_builder(3)
>>>> [[3, ' ', '*', ' ', ' '], [' ', ' ', '*', ' ', ' '], [' ', ' ', '*', ' ', ' ']]

I must have some sort of fundamental misunderstanding on how lists work for this to happen. Can someone explain why this is happening?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

0 Answers0