Take the 2-minute tour ×

I'm writing a Python script that reads a CSV file and creates a list of deques. If I print out exactly what gets appended to the list before it gets added, it looks like what I want, but when I print out the list itself I can see that append is overwriting all of the elements in the list with the newest one.

    # Window is a list containing many instances            
def slideWindow(window, nextInstance, num_attributes):
    attribute = nextInstance.pop(0)
    for i in range(num_attributes):
    return window

def convertDataFormat(filename, window_size):
    with open(filename, 'rU') as f:
        reader = csv.reader(f)

        window = deque()
        alldata = deque()

        i = 0
        for row in reader:
            if i < (window_size-1):


        for row in reader:
            window = slideWindow(window, row, NUM_ATTRIBUTES)
#             print alldata

        return alldata
share|improve this question
Side note: When you use with open(...), you don't need to close the file. In fact, that's one of the advantages of context managers. –  delnan Aug 10 '12 at 2:20

2 Answers 2

up vote 1 down vote accepted

This is really difficult to track what you exactly want from this code. I suspect the problem lies in the following:


for row in reader:
    window = slideWindow(window, row, NUM_ATTRIBUTES)

Notice that in your slideWindow function, you modify the input deque (window), and then return the modified deque. So, you're putting a deque into the first element of your list, then you modify that object (inside slideWindow) and append another reference to the same object onto your list.

Is that what you intend to do?

The simple fix is to copy the window input in slideWindow and modify/return the copy.

share|improve this answer
Sorry my code is so confusing. I didn't know that Python passed everything by reference, so I had to make a copy of window and then add it to alldata. Thanks for your help! –  AJ Jenkins Aug 10 '12 at 4:09

I don't know for sure, but I'm suspicious it might be similar to this problem http://forums.devshed.com/python-programming-11/appending-object-to-list-overwrites-previous-842713.html.

share|improve this answer

Your Answer


