
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Python – Group Consecutive elements by Sign
When it is required to group consecutive elements by sign, the ‘^’ operator and the simple iteration along with ‘enumerate’ is used.
Below is a demonstration of the same −
Example
my_list = [15, -33, 12, 64, 36, -12, -31, -17, -49, 12, 43, 30, -23, -35, 53] print("The list is :") print(my_list) my_result = [[]] for (index, element) in enumerate(my_list): if element ^ my_list[index - 1] < 0: my_result.append([element]) else: my_result[-1].append(element) print("The result is :") print(my_result)
Output
The list is : [15, -33, 12, 64, 36, -12, -31, -17, -49, 12, 43, 30, -23, -35, 53] The result is : [[15], [-33], [12, 64, 36], [-12, -31, -17, -49], [12, 43, 30], [-23, -35], [53]]
Explanation
A list is defined and is displayed on the console.
An empty list of list is defined.
The list is iterated using ‘enumerate’, and the ‘^’ operator is used to check if the specific element is less than 0.
If yes, it is appended to the empty list.
Otherwise, it is appended to the end of the list.
This is displayed as the output on the console.
- Related Articles
- Compress array to group consecutive elements JavaScript
- Python – Filter consecutive elements Tuples
- Python – Reorder for consecutive elements
- Python – Consecutive identical elements count
- How to group Python tuple elements by their first element?
- Swap Consecutive Even Elements in Python
- Python – Summation of consecutive elements power
- Python Program to Sort Matrix Rows by summation of consecutive difference of elements
- Consecutive elements pairing in list in Python
- Python – Grouped Consecutive Range Indices of Elements
- Check if array elements are consecutive in Python
- Python program to count pairs for consecutive elements
- Count Subarrays with Consecutive elements differing by 1 in C++
- Check if Queue Elements are pairwise consecutive in Python
- Program to pack same consecutive elements into sublist in Python

Advertisements