Here is a problem I had to do:
We are going to implement a very helpful function, called group.
group takes a list of things and returns a list of group, where each group is formed by all equal consecutive elements in the list.
For example:
group([1, 1, 1, 2, 3, 1, 1]) == [[1, 1, 1], [2], [3], [1, 1]]
group([1, 2, 1, 2, 3, 3]) == [[1], [2], [1], [2], [3, 3]]
And here is my initial solution:
def group(int_list):
group_list = []
current_list = []
for i in range(len(int_list)):
if int_list[i] not in current_list:
if len(current_list) != 0:
group_list.append(current_list)
del current_list[:]
current_list.append(int_list[i])
else:
current_list.append(int_list[i])
group_list.append(current_list)
return group_list
And the output I was getting:
[[1, 1], [1, 1], [1, 1], [1, 1]]
After spending like 30 minutes trying to figure out the problem, I changed the 9th line from group_list.append(current_list)
to group_list.append(current_list[:])
and surprisingly the magic worked. I got the correct output:
[[1, 1, 1], [2], [3], [1, 1]]
So I guess my question is what's the difference between current_list
and current_list[:]
?