Open In App

Python – Find starting index of all Nested Lists

Improve
Improve
Like Article
Like
Save
Share
Report

In this article given a matrix, the task is to write a Python program to compute the starting index of all the nested lists.

Example:

Input : test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
Output : [0, 1, 5, 7, 13]
Explanation : 1 + 4 = lengths of 2 initial lists = 5, 3, of 3rd list start 
                    from 5th index [ 0 based indexing ], 
                    hence 5. as 3rd element in result list.
Input : test_list = [[5], [9, 3, 1, 4], [3, 2], [3, 4, 5]]
Output : [0, 1, 5, 7]
Explanation : 1 + 4 = lengths of 2 initial lists = 5, 3, of 3rd list start 
                from 5th index [ 0 based indexing ],
                hence 5. as 3rd element in result list.

Method #1 : Using loop + len()

In this, length of each sublist is computed using len() and summed, cumulatively, and added as an intermediate result. The initial index is derivative of the lengths of sublists.

Python3




# Python3 code to demonstrate working of
# Initial element index in Matrix
# Using loop
 
# initializing list
test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = []
lens = 0
for sub in test_list:
 
    # lengths of sublist computed
    res.append(lens)
    lens += len(sub)
 
# printing result
print("Initial element indices : " + str(res))


Output:

The original list is : [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
Initial element indices : [0, 1, 5, 7, 13]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2 : Using accumulate() + map() + len()

In this, we perform the task of getting summation using accumulate(), map() is used to get lengths of all the sublists computed using len(). 

Python3




# Python3 code to demonstrate working of
# Initial element index in Matrix
# Using accumulate() + map() + len()
from itertools import accumulate
 
# initializing list
test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# ignoring last index using "-1"
# sum starting at 0
res = [0, *accumulate(map(len, test_list[:-1]))]
 
# printing result
print("Initial element indices : " + str(res))


Output:

The original list is : [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
Initial element indices : [0, 1, 5, 7, 13]

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. The accumulate() + map() + len() is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n), new list of size O(n) is created where n is the number of elements in the list

Method #3 : Using type() and loop and a if statement

In this, we simply check the type of the element in the list if it’s another list we print its index otherwise not. This method will work regardless of the number of non-list type elements in the list

Python3




# This will print all the starting indexes
# of sublists inside this list
lis = [[1, 2, 3], 4, 5, [6, 7, 8], 9, 0, [10]]
 
for i in lis:
    if type(i) == list:
        print(lis.index(i), end=",")
 
# This code is contributed by BABAji


Output:

0,3,6,

Method #4: Using reduce() function from functools + lambda()

Algorithm:

  1. Reduce the test_list to a list of cumulative lengths of its sublists, starting from 0.
  2. Append 0 to the beginning of the list of cumulative lengths.
  3. Remove the last element from the list of cumulative lengths.
  4. Return the resulting list as the indices of the initial elements of the sublists in the original list.

Python3




# importing reduce from functools
from functools import reduce
# initializing list
test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
res = [0] + list(reduce(lambda x, y: x +
                        [len(y) + x[-1]], test_list, [0])[1:-1])
 
# printing result
print("Initial element indices : " + str(res))


Output

The original list is : [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
Initial element indices : [0, 1, 5, 7, 13]

Time Complexity: O(n), where n is the number of elements in the input list because the reduce function iterates through the sublists of the input list exactly once.
Auxiliary Space: O(n), because it creates a new list of cumulative lengths that have the same length as the input list. 

Method #4: Using Recursion

Algorithm:

  • Check if the input list is empty using the not keyword.
  • If the list is empty, return an empty list.
  • Otherwise, recursively call the get_starting_indices function on the remaining sublists in the input list, starting from the second sublist.
  • Add the length of the first sublist to each starting index returned by the recursive call to get the starting indices of the current sublist.
  • Call the get_starting_indices function 
  • Print the resulting list of starting indices.

Python3




def get_starting_indices(test_list):
   # base case
   if not test_list:
       return []
   else:
      # Recursively get the starting indices of the remaining sublists and add the length of the first sublist
       # to each index to get the starting indices of the current list.
       return [0] + [len(test_list[0]) + i for i in get_starting_indices(test_list[1:])]
 
# initializing list
test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
#function call
res = get_starting_indices(test_list)
 
# printing result
print("Initial element indices : " + str(res))


Output

The original list is : [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
Initial element indices : [0, 1, 5, 7, 13]

Time Complexity: O(n*n) because the function makes a recursive call for each sublist in the input list, and for each recursive call, it slices the input list to get the remaining sublists
Auxiliary Space: O(n), a new list of size O(n) is created where n is the number of elements in the list

Method #5: Using enumerate() function to get the cumulative length of the sublists

Steps:

  1. Initialize an empty list “res” and a variable “cumulative_length” to 0.
  2. Loop through each sublist in the input list using a for loop and the enumerate function
  3. Append the current value of the “cumulative_length” variable to the “res” list
  4. Add the length of the current sublist to the “cumulative_length” variable
  5. Print the final “res” list

Python3




# initializing list
test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
 
res = []
cumulative_length = 0
 
# printing original list
print("The original list is : " + str(test_list))
 
# iterate through the list
for i, sub in enumerate(test_list):
    res.append(cumulative_length)
    cumulative_length += len(sub)
 
# printing result
print("Initial element indices : " + str(res))


Output

The original list is : [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
Initial element indices : [0, 1, 5, 7, 13]

Time Complexity: O(n), where n is the total number of elements in the input list
Space Complexity: O(n), where n is the total number of elements in the input list 

Method #6: Using list comprehension and sum()

step-by-step approach

  1. Create a list of sublists test_list with the given input values: [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]].
  2. Use a list comprehension to iterate through each sublist in test_list and calculate the length of all previous sublists.
  3. For each sublist, use another list comprehension to loop through all previous sublists up to the current sublist, and calculate the length of each sublist.
  4. Use the sum() function to add up the lengths of all previous sublists for each sublist.
  5. Use the range() function to iterate through the indices of the list of sublists.
  6. For each index i, use the list comprehension from step 2 to calculate the initial element index for the i-th sublist.
  7. Store the result in a list res.
  8. Print the result using the print() function.
  9. The output will be a list of initial element indices for each sublist: [0, 1, 5, 7, 13].

Python3




test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
 
res = [sum(len(sublist) for sublist in test_list[:i]) for i in range(len(test_list))]
 
print("Initial element indices : " + str(res))


Output

Initial element indices : [0, 1, 5, 7, 13]

The time complexity of this method is O(n^2), where n is the total number of elements in the matrix.

 The auxiliary space complexity is O(n).



Last Updated : 22 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads