I'd like to append a list to another list, then use the first as a template for another entry to be appended to the top level list. But when I modify the lower list, the upper list gets modified.
trip = []
trips = []
trip_day = [1, 2]
bd_year = '2020'
bd_start_mo = 7
leg_dates = []
days = [7, 14]
leg1 = {'leg_date': 7, 'item2': 'green'}
leg2 = {'leg_date': 7, 'item2': 'red'}
trip = [leg1, leg2]
for idx,day in enumerate(days): # loop thru each instance of trip
for leg in trip_day: # loop thru each leg in a trip
# build list of actual dates for each leg
leg_dates.append(day + (leg - 1))
for leg in range(0,len(trip_day)): # loop thru each leg and update actual date in the dict
trip[leg]['leg_date'] = leg_dates[leg]
a = list(trip)
trips.append(a)
print(trips)
leg_dates = []
a =[]
This results in:
[[{'leg_date': 14, 'item2': 'green'}, {'leg_date': 15, 'item2': 'red'}],
[{'leg_date': 14, 'item2': 'green'}, {'leg_date': 15, 'item2': 'red'}]]
I would expect the first two entries to have leg_dates of 7 and 8 not 14 and 15. I tried using list() and using an intermediate list "a" to copy to with no success.
So how do I keep "trips" from changing when I modify "trip", or in other words, how do I append values and not references to lists? "extend" is not what I want. My "Crash Course in Python" book doesn't mention this. This is very frustrating as I'm coming from a C/MATLAB background.