Trick on Appending a List to Another List in Python

Today I spent some time on practicing coding. When I was trying to solve a problem about finding paths with elements whose sum equals to a specified value, given a binary tree and a value, I stumble against some unknown problems. 

As I firstly finished my code, I got a null result. My codes at beginning was like this. 

Can you guys find where the problem lies?

Actually, the problem happens when I was trying to append a path to the res list followed by pop operation. You may better understand with the example below. 

I bet now you must realize the appending here is about passing by reference. What is appended to the list a is just a reference of list b. When you modify the b, the corresponding content in a will also change. 

In this way, I have to reassign another list and copy the content from b to this list. That is

Finally, I got the correct answer. 

Leave a Reply

Your email address will not be published. Required fields are marked *