0

I have a list called trips which contains lists of trip which are in turn dictionaries of legs.
So for instance there are 4 legs in a trip, and there hundreds of trip in trips.

When generating trip entries, I use the previous one and just update leg_date and then append that trip to trips.

However, when I change the leg_date entry in trip, it automagically changes the leg_date value in the previous trip that I had just appended to trips.
In other words, when I change trip it's also changing trips. It's almost as if trips contains pointers to trip.

I would expect the output to have leg_dates of 7/7 and 7/8 for the first entry and 7/14 and 7/15 for the second. Instead I get both entries having leg_dates of 7/14 and 7/15.

Output:

[[{'leg_date': datetime.date(2020, 7, 14), 'item2': 'green'},  
{'leg_date': datetime.date(2020, 7, 15), 'item2': 'red'}],  
[{'leg_date': datetime.date(2020, 7, 14), 'item2': 'green'},  
{'leg_date': datetime.date(2020, 7, 15), 'item2': 'red'}]]

Sample code:

from datetime import date
from datetime import datetime
from datetime import timedelta

trip = []
trips = []

trip_day = [1, 2]
bd_year = '2020'
bd_start_mo = 7
leg_dates = []
days = [7, 14]

leg1 = {'leg_date': '2020-07-07', 'item2': 'green'}
leg2 = {'leg_date': '2020-07-07', '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(date(int(bd_year), bd_start_mo, day) + timedelta(days = (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]

    trips.append(trip)
    print(trips)
    leg_dates = []
  #  trip = [leg1, leg2]
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
  • 1
    "It's almost as if "trips" contains pointers to trip" - you are right – rdas May 09 '20 at 18:57
  • "The below code will not run for you as there are over 400 lines of code with non public info.": make an mcve please – Mad Physicist May 09 '20 at 19:34
  • ""It's almost as if "trips" contains pointers to trip" - you are right – rdas" But I used the .append method to add trip to trips which is a list of dictionaries. Doesn't "append" just add the values and not add a reference? – brockenspectre May 09 '20 at 22:45

0 Answers0