Python - Find starting index of all Nested Lists

When working with nested lists, you might need to find the starting index of each sublist if all elements were flattened into a single list. This is useful for indexing and data processing tasks.

Understanding the Problem

Given a nested list like [[51], [91, 22, 36, 44], [25, 25]], if we flatten it to [51, 91, 22, 36, 44, 25, 25], we want to know where each original sublist starts: [0, 1, 5].

Method 1: Using Simple Iteration

Track the cumulative length as we iterate through each sublist ?

my_list = [[51], [91, 22, 36, 44], [25, 25], [46, 67, 78, 82, 69, 29], [7, 5]]
print("The list is :")
print(my_list)

my_result = []
my_len = 0
for sub in my_list:
    my_result.append(my_len)
    my_len += len(sub)

print("The starting indices are :")
print(my_result)
The list is :
[[51], [91, 22, 36, 44], [25, 25], [46, 67, 78, 82, 69, 29], [7, 5]]
The starting indices are :
[0, 1, 5, 7, 13]

Method 2: Using List Comprehension with enumerate

A more concise approach using cumulative sum ?

my_list = [[51], [91, 22, 36, 44], [25, 25], [46, 67, 78, 82, 69, 29], [7, 5]]

# Calculate cumulative lengths
cumulative_lengths = [0]
for sub in my_list[:-1]:  # Exclude last element
    cumulative_lengths.append(cumulative_lengths[-1] + len(sub))

print("Starting indices using cumulative sum:")
print(cumulative_lengths)
Starting indices using cumulative sum:
[0, 1, 5, 7, 13]

Method 3: Using itertools.accumulate

The most Pythonic approach using built-in functions ?

import itertools

my_list = [[51], [91, 22, 36, 44], [25, 25], [46, 67, 78, 82, 69, 29], [7, 5]]

# Get lengths of all sublists
lengths = [len(sub) for sub in my_list]

# Calculate starting indices using accumulate
starting_indices = [0] + list(itertools.accumulate(lengths[:-1]))

print("Starting indices using itertools.accumulate:")
print(starting_indices)
Starting indices using itertools.accumulate:
[0, 1, 5, 7, 13]

How It Works

Each method calculates where each sublist would start in a flattened version:

  • First sublist [51] starts at index 0

  • Second sublist [91, 22, 36, 44] starts at index 1 (after 1 element)

  • Third sublist [25, 25] starts at index 5 (after 1 + 4 = 5 elements)

  • And so on...

Comparison

Method Readability Performance Best For
Simple Iteration High Good Beginners, clear logic
List Comprehension Medium Good Intermediate users
itertools.accumulate High Best Pythonic, functional style

Conclusion

All three methods effectively find starting indices of nested lists. Use simple iteration for clarity, or itertools.accumulate for the most Pythonic approach. The choice depends on your coding style and requirements.

---
Updated on: 2026-03-26T02:07:27+05:30

459 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements