Possible Duplicate:
What is the difference between LIST.append(1) and LIST = LIST + [1] (Python)
I’m new to Python and new to programming. I followed the book ThinkPython and here is one thing I can’t get straight.
Exercise 10.7 Write a function that reads the file words.txt and builds a list with one element per word. Write two versions of this function, one using the append method and the other using the idiom t = t + [x]. Which one takes longer to run? Why?
I tried the two methods and found the later one (t=t+[x]) took much longer time than append method. Here is my first question, why would this happen?
I changed the line t=t+[x] to t+=[x] just for no reason only to find this revised version take almost the same time as the append method. I thought t=t+[x] is equal to t+=[x], apparently they are not. Why?
BTW: I tried search Google using python += as key words but it seems Google won’t take += as a key word even I put a quotation mark to it.
takes
t, concatenates with[x](callingt‘s method__add__), which creates a new list, which is then namedt.calls the
t‘s method__iadd__which works directly on the list itself. There is no extra list created.