Python logic

Why does when we assign a list into a variable like in “attractions_for_destination = attractions[destination_index]” and we modify(append) that variable(attractions_for_destination). The list(attractions) got modify. It should have only modify the variable not the original list.

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

attractions is a list of lists i.e. having a structure like [ [], [], [], ... ]

attractions[destination_index] selects one of these sublists.

When you make the assignment,

attractions_for_destination = attractions[destination_index]

you aren’t making a copy of the sublist. Instead the variable attractions_for_destination is being assigned a reference to this sublist.

Consider the examples,

x = [1, 2, 3]
y = x # Not a copy. Reference has been assigned.
y.append(55)
print(y)
# [1, 2, 3, 55]
print(x)
# [1, 2, 3, 55]
####
x = [["a", "b"], ["g"], ["g", "k"], ["s", "t", "u"]]

# This is not a copy of the list. 
# The reference to the third sublist has been assigned to the variable y.
y = x[2] 

print(y)
#
# ['g', 'k']
#

y.append("z")
print(y)
#  
# ['g', 'k', 'z']
#

print(x)
#  
# [['a', 'b'], ['g'], ['g', 'k', 'z'], ['s', 't', 'u']]
#