
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python – Grouped Consecutive Range Indices of Elements
When it is required to get the grouped consecutive range of indices of elements in a list, a defaultdict is created. A simple iteration, along with ‘groupby’ method, ‘len’ method, ‘list’ method and the ‘append’ methods are used.
Example
Below is a demonstration of the same −
from itertools import groupby from collections import defaultdict my_list = [63, 12, 84, 91, 52, 39, 25, 27, 20, 11, 0,9] print("The list is : " ) print(my_list) my_index = 0 my_result = defaultdict(list) for key, sub in groupby(my_list): element = len(list(sub)) my_result[key].append((my_index, my_index + element - 1)) my_index += element print("The resultant dictionary is : ") print(my_result)
Output
The list is : [63, 12, 84, 91, 52, 39, 25, 27, 20, 11, 0, 9] The resultant dictionary is : defaultdict(, {63: [(0, 0)], 12: [(1, 1)], 84: [(2, 2)], 91: [(3, 3)], 52: [(4, 4)], 39: [(5, 5)], 25: [(6, 6)], 27: [(7, 7)], 20: [(8, 8)], 11: [(9, 9)], 0: [(10, 10)], 9: [(11, 11)]})
Explanation
The required packages are imported into the environment.
A list of integers is defined and is displayed on the console.
A value is initialized to 0.
A default dictionary is created.
The list is iterated over by applying the ‘groupby’ method on it.
The initialized value is appended to the empty dictionary.
This is displayed as the output on the console.
- Related Articles
- Python – Extract range of Consecutive similar elements ranges from string list
- Python – Summation of consecutive elements power
- Find elements of a list by indices in Python
- Python – Filter consecutive elements Tuples
- Python – Reorder for consecutive elements
- Python – Consecutive identical elements count
- Python Program to repeat elements at custom indices
- Swap Consecutive Even Elements in Python
- Python – Group Consecutive elements by Sign
- Python program to remove elements at Indices in List
- Assign range of elements to List in Python
- Consecutive elements pairing in list in Python
- Delete elements in range in Python
- Python – Filter Rows with Range Elements
- Python Grouped Flattening of list

Advertisements