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:
- Reduce the test_list to a list of cumulative lengths of its sublists, starting from 0.
- Append 0 to the beginning of the list of cumulative lengths.
- Remove the last element from the list of cumulative lengths.
- 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))
OutputThe 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))
OutputThe 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:
- Initialize an empty list "res" and a variable "cumulative_length" to 0.
- Loop through each sublist in the input list using a for loop and the enumerate function
- Append the current value of the "cumulative_length" variable to the "res" list
- Add the length of the current sublist to the "cumulative_length" variable
- 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))
OutputThe 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
- 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]].
- Use a list comprehension to iterate through each sublist in test_list and calculate the length of all previous sublists.
- 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.
- Use the sum() function to add up the lengths of all previous sublists for each sublist.
- Use the range() function to iterate through the indices of the list of sublists.
- For each index i, use the list comprehension from step 2 to calculate the initial element index for the i-th sublist.
- Store the result in a list res.
- Print the result using the print() function.
- 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))
OutputInitial 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).
Similar Reads
Find the Index of a Substring in Python
Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python.Using str.find() The find() method searches for the first occurrence of the specified substring and return
3 min read
Python program to find String in a List
Searching for a string in a list is a common operation in Python. Whether we're dealing with small lists or large datasets, knowing how to efficiently search for strings can save both time and effort. In this article, weâll explore several methods to find a string in a list, starting from the most e
3 min read
Python | Find number of lists in a tuple
Given a tuple of lists, the task is to find number of lists in a tuple. This is a very basic problem but can be useful while making some utility application. Method #1: Using len Python3 # Python code to find number of list in a tuple # Initial list Input1 = ([1, 2, 3, 4], [5, 6, 7, 8]) Input2 = ([1
4 min read
Python - Find Index containing String in List
In this article, we will explore how to find the index of a string in a list in Python. It involves identifying the position where a specific string appears within the list.Using index()index() method in Python is used to find the position of a specific string in a list. It returns the index of the
2 min read
Python - Negative index of Element in List
We are given a list we need to find the negative index of that element. For example, we are having a list li = [10, 20, 30, 40, 50] and the given element is 30 we need to fin the negative index of it so that given output should be -3.Using index()index() method in Python searches for the first occur
3 min read
How to Find Index of a Substring in Python
In Python, sometimes we need to know where a certain substring appears in a string. To do this, we can find the index (or position) of that substring. The index tells us where the substring is located. Letâs look at some simple ways to find the index of a substring in a string.Using find() methodThe
2 min read
Python | Split nested list into two lists
Given a nested 2D list, the task is to split the nested list into two lists such that the first list contains the first elements of each sublist and the second list contains the second element of each sublist. In this article, we will see how to split nested lists into two lists in Python. Python Sp
5 min read
Python | Search in Nth column in list of tuples
Sometimes, while working with Python list, we can have a data set that consists of tuples and we have a problem in which we need to search the element in the Nth column of list. This has it's applications in web development domain. Let's discuss certain ways in which this task can be performed. Meth
7 min read
Python - Start and End Indices of words from list in String
Given a String, our task is to write a Python program to extract the start and end index of all the elements of words of another list from a string. Input : test_str = "gfg is best for all CS geeks and engineering job seekers", check_list = ["geeks", "engineering", "best", "gfg"]Output : {'geeks': [
7 min read
How to Find Index of Item in Python List
To find the index of given list item in Python, we have multiple methods depending on specific use case. Whether weâre checking for membership, updating an item or extracting information, knowing how to get an index is fundamental. Using index() method is the simplest method to find index of list it
2 min read