0

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.

  • You are appending values, the value *is the object*. You keep appending *the same object*. You want to add a *copy* of the object, so use `.append(trip.copy())` Although note, that will only create a shallow copy. In this case, you could just do `.append([d.copy() for d in trip])` – juanpa.arrivillaga May 11 '20 at 20:16
  • if you want to append a shallow copy you can use `trips.append(a[:])` if you want a deep copy you will need to use `copy` from the stdlib – gold_cy May 11 '20 at 20:17
  • Just build `a` as a new list: `a = [{'leg_date': leg_dates[leg], 'item2': trip[leg]['item2'] for leg in range(len(trip_day))]` – Samwise May 11 '20 at 20:18

1 Answers1

0
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)


    leg_dates = []
    a =[]


    print(trip)

output

[{'leg_date': 7, 'item2': 'green'}, {'leg_date': 8, 'item2': 'red'}]
[{'leg_date': 14, 'item2': 'green'}, {'leg_date': 15, 'item2': 'red'}]
Rima
  • 1,447
  • 1
  • 6
  • 12