0

Can you help me with this code?

s = [1, 1, 3, 3, 2, 2, 2, 2, 1, 1, 2, 2, 2]

def group(s):
    lst = []
    temp_lst = []
    for i in s:
        if len(temp_lst) == 0:
            temp_lst.append(i)
            continue
        if temp_lst[0] == i:
            temp_lst.append(i)
        else:
            lst.append(temp_lst)
            del temp_lst[:]
            temp_lst.append(i)
    return lst

It returns:

[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]]

Why?

My desired output is:

[[1, 1], [3, 3], [2, 2, 2, 2], [1, 1], [2, 2, 2]]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
a_z_s
  • 29
  • 1
  • 1
    You are filling the outer list with references to the same inner list; `del tmp_lst[:]` empties the existing list, you never create a new one. Also note that `itertools.groupby` would help you out. – jonrsharpe Jan 21 '17 at 10:11
  • Using [`itertools.groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby): `[list(g) for _, g in groupby(s)]` – PM 2Ring Jan 21 '17 at 10:41

1 Answers1

2

This works: Replaced del temp_lst[:] by temp_lst = []

s = [1, 1, 3, 3, 2, 2, 2, 2, 1, 1, 2, 2, 2]

def group(s):
    lst = []
    temp_lst = []
    for i in s:
        if len(temp_lst) == 0:
            temp_lst.append(i)
            continue
        if temp_lst[0] == i:
            temp_lst.append(i)
        else:
            lst.append(temp_lst)
            temp_lst = []
            temp_lst.append(i)
    lst.append(temp_lst)
    return lst

print group(s)

Output:

[[1, 1], [3, 3], [2, 2, 2, 2], [1, 1], [2, 2, 2]]

What del temp_lst[:] does is that it deletes all entries of the list. The key to understand here is that you operate by reference and you need to point temp_list to a new list so you don't operate on the old list you just put into lst

Doing temp_list = [] leaves the old list (which you just inserted into lst) and assigns the variable (you can think of a pointer) to a new empty list which is not associated with the just inserted list.

As jonrsharpe correctly notes above a better solution would be itertools.groupby:

s = [1, 1, 3, 3, 2, 2, 2, 2, 1, 1, 2, 2, 2]
[list(l[1]) for l in itertools.groupby(s)]

Output:

[[1, 1], [3, 3], [2, 2, 2, 2], [1, 1], [2, 2, 2]]
hansaplast
  • 11,007
  • 2
  • 61
  • 75