Home > Net >  Unexpected loop behavior when appending lists
Unexpected loop behavior when appending lists

Time:02-01

I wanted to know why the below code works as expected. The aim was to make a list of lists, where each inner list contains books from a particular author. A friend accidentally appended into the temporary list right after the temporary list's declaration and the code still worked. I was appending after the inner-for loop, which works like normal.

Code:

all_books = []
for author in os.listdir("books/"):
    tmp = []

    all_books.append(tmp)

    for book in os.listdir("books/"   author   "/"):
        tmp.append(book)

print(all_books)

Output:

[['On_the_Origin_of_Species.txt', 'The_Power_of_Movement_in_Plants.txt'],
 ['Adventures_of_Sherlock_Holmes.txt',
  'Memoirs_of_She rlock_Holmes.txt',
  'The_Lost_World.txt'],
 ['A_Treatise_of_Human_Nature.txt', 'An_Enquiry_Concerning_Human_Understanding.txt'],
 ['Treasure_Island.txt'],
 ['Ivanhoe A_Romance.txt', 'The_Lady_of_the_Lake.txt']]

CodePudding user response:

When you assign tmp into all_data. Instead of creating a new copy of tmp, it makes a reference of tmp variable. That's causes this issue.

Identical objects have the same id in python. If id is same then name references to same variable.

all_data = []
tmp = []
all_data.append(tmp)
print("all_data_tmp id",id(all_data[0]))
print("tmp id",id(tmp))
tmp.append(2)
print("all_data",all_data)

Output:

all_data_tmp id 2322674224840
tmp id 2322674224840
all_data [[2]]
  •  Tags:  
  • Related