 GeeksforGeeks App
Open App Browser
Continue

# Python – Group Consecutive elements by Sign

Given a list group of consecutive elements on the basis of signs.

```Input : test_list = [5, -3, 2, 4, 6, -2, -1, -7, -9, 2, 3]
Output : [, [-3], [2, 4, 6], [-2, -1, -7, -9], [2, 3]]
Explanation : Elements inserted into new list on sign change.```
```Input : test_list = [-2,3,4,5,6,-3]
Output : [[-2], [3, 4, 5, 6], [-3]]
Explanation : Elements inserted into new list on sign change.  ```

Method #1: Using the loop

In this, whenever a sign(positive or negative) change occurs, a new list is initiated otherwise the elements are appended to a similar list as initialized.

## Python3

 `# Python3 code to demonstrate working of``# Group Consecutive elements by Sign``# Using loop` `# initializing list``test_list ``=` `[``5``, ``-``3``, ``2``, ``4``, ``6``, ``-``2``, ``-``1``, ``-``7``,``             ``-``9``, ``2``, ``3``, ``10``, ``-``3``, ``-``5``, ``3``]` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))` `res ``=` `[[]]``for` `(idx, ele) ``in` `enumerate``(test_list):` `    ``# checking for similar signs by XOR``    ``if` `ele ^ test_list[idx ``-` `1``] < ``0``:``        ``res.append([ele])``    ``else``:``        ``res[``-``1``].append(ele)` `# printing result``print``(``"Elements after sign grouping : "` `+` `str``(res))`

Output

```The original list is : [5, -3, 2, 4, 6, -2, -1, -7, -9, 2, 3, 10, -3, -5, 3]
Elements after sign grouping : [, [-3], [2, 4, 6], [-2, -1, -7, -9], [2, 3, 10], [-3, -5], ]
```

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using groupby() + list comprehension

In this, we perform the task of grouping using groupby(), and list comprehension is used to perform the task of iterating through the list. The condition for the sign is injected using the lambda function.

## Python3

 `# Python3 code to demonstrate working of``# Group Consecutive elements by Sign``# Using groupby() + list comprehension` `import` `itertools` `# initializing list``test_list ``=` `[``-``2``, ``3``, ``4``, ``5``, ``6``, ``-``3``]` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))` `# grouped using groupby()``res ``=` `[``list``(ele) ``for` `idx, ele ``in` `itertools.groupby(test_list, ``lambda` `a: a > ``0``)]` `# printing result``print``(``"Elements after sign grouping : "` `+` `str``(res))`

Output

```The original list is : [-2, 3, 4, 5, 6, -3]
Elements after sign grouping : [[-2], [3, 4, 5, 6], [-3]]
```

Time Complexity: O(n), where n is the length of the input list. This is because we’re using the built-in groupby() + list comprehension which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), where n is the length of the input list as we’re using additional space other than the input list itself.

Method 3: using the numpy library

Steps:

1. Import the numpy library.
2. Initialize the input list test_list.
3. Convert the input list to a numpy array using the numpy.array() method.
4. Create a boolean array by checking if each element in the numpy array is greater than zero using the numpy.greater() method.
5. Use the numpy.split() method to split the numpy array into sub-arrays based on the boolean array created in step 4.
6. Convert each sub-array to a list using the tolist() method.
7. Print the result.

## Python3

 `import` `numpy as np` `# initializing list``test_list ``=` `[``-``2``, ``3``, ``4``, ``5``, ``6``, ``-``3``]` `# convert to numpy array``arr ``=` `np.array(test_list)` `# create boolean array``bool_arr ``=` `np.greater(arr, ``0``)` `# split array based on boolean array``res_arr ``=` `np.split(arr, np.where(bool_arr[:``-``1``] !``=` `bool_arr[``1``:])[``0``]``+``1``)` `# convert each sub-array to a list``res ``=` `[i.tolist() ``for` `i ``in` `res_arr]` `# print result``print``(``"Elements after sign grouping : "` `+` `str``(res))`

```OUTPUT :
Elements after sign grouping : [[-2], [3, 4, 5, 6], [-3]]```

Time complexity: O(n)
Auxiliary space: O(n)

My Personal Notes arrow_drop_up