Simple question out of curiosity

Hello all! I am new to Code Academy and firs time posting on these forums. I am on the Computer science path and got to an interesting (to me) point in the first big project i got to: The Bordeless Tourist

Steps 27-35; My initial idea was the same as the walkthrough video

Blockquote
def add_attraction(destination, attraction):
try:
destination_index = get_destination_index(destination)
attractions[destination_index].append(attraction)

this will append the new attraction to the master attractions list

However when I followed the steps in the lesson I ended up with different code

Blockquote
def add_attraction(destination, attraction):
try:
destination_index = get_destination_index(destination) # per step 29
attractions_for_destination = attractions[destination_index] # per step 32
attractions_for_destination.append(attraction) # per step 33
except ValueError :
return
add_attraction(“Los Angeles, USA”, [“Venice Beach”, [“beach”]])
print(attractions) # print is outside of the function and uses the attractions variable which we did not edit

My expectation was that this would print a list containing five empty lists, since the function does not append to attractions but to attractions_for_destination instead. However the results from print was

Blockquote
[, , [[‘Venice Beach’, [‘beach’]]], , ]

Why did attractions change in this situation?

Thank you for your answers.

1 Like

Hi @codesalad,

This statement assigns a reference to the item within attractions that is at destination_index:

attractions_for_destination = attractions[destination_index] # per step 32

Thereafter, a statement that uses attractions_for_destination actually refers directly to that item. It is a genuine reference to the item, rather than merely a reference to a copy of that item.

Accordingly, this statement makes a direct change to attractions:

attractions_for_destination.append(attraction) # per step 33

That is how attractions got changed.

2 Likes