

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Compress array to group consecutive elements JavaScript
- How to group Python tuple elements by their first element?
- Swap Consecutive Even Elements in Python
- Python – Filter consecutive elements Tuples
- Python – Reorder for consecutive elements
- Python – Consecutive identical elements count
- Python Program to Sort Matrix Rows by summation of consecutive difference of elements
- Consecutive elements pairing in list in Python
- Python – Summation of consecutive elements power
- Count Subarrays with Consecutive elements differing by 1 in C++
- Check if array elements are consecutive in Python
- Python – Grouped Consecutive Range Indices of Elements
- Python program to count pairs for consecutive elements
- Listing all rows by group with MySQL GROUP BY?
- Group-by and Sum in Python Pandas
Advertisements