0
Appending a list to a list not working as I thought it would.
group = [] groups = [] numlist = [x for x in range(1, 21)] for x in numlist: group.append(x) if len(group) == 5: groups.append(list(group)) # <-- why this way and not groups.append(group) group.clear() print(groups) https://code.sololearn.com/cKKe3fZTDt6J/#py
3 Answers
+ 4
The reason is the use of group.clear(). What you do is to use group as a kind of buffer to collect some values, and then you append it to an other list groups. So these appended elements are a copy of group. You can check this with printing the id's. If you then clear group, also the appended data in groups will be removed. You can avoid this by using
group = [] instead of group.clear()
Then you can work as expected with:
groups.append(group)
+ 3
If you use
groups.append(group) # without list()
reference to the same list 'group' is appended to 'groups' 5 times (not a copy of list 'group').
So, at the end of the loop 'groups' will contain 5 references to the same list 'group'. As 'group' is cleared after appending, 'groups' will contain 5 empty lists (5 references to the empty list 'group').
When your use list()
groups.append(list(group))
list() creates a copy of 'group' reference to which is appended to 'groups'. So, at the end of the loop all items of 'groups' will refer to the different lists. And you will get the expected output.
+ 1
Thank you for your replies....It's going to take some time to get my head round (understand) the explanations (lol).......but..... I'll get there...thank you again.