Python - Find starting index of all Nested Lists


When it is required to find the starting index of all nested lists, a simple iteration along with the ‘append’ method is used.

Example

Below is a demonstration of the same

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 initial element indices are :")
print(my_result)

Output

The list is :
[[51], [91, 22, 36, 44], [25, 25], [46, 67, 78, 82, 69, 29], [7, 5]]
The initial element indices are :
[0, 1, 5, 7, 13]

Explanation

  • A list of list is defined and is displayed on the console.

  • An empty list is defined, and an integer is assigned to 0.

  • The list is iterated over, and the integer is appended to the empty list.

  • The integer is incremented based on element in the list.

  • This empty list which is now populated is the result.

  • It is displayed as output on the console.

Updated on: 15-Sep-2021

291 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements