How do you find the index of an element in a nested list?

Python – Find starting index of all Nested Lists

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 intermediate result. The initial index is derivative of lengths of sublists.




# 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]

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

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




# 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]

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




# 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,

How do you find the index of an element in a nested list?




Article Tags :

Python

Python Programs

Python list-programs

Python | Indexing a sublist

In Python, we have several ways to perform the indexing in list, but sometimes, we have more than just an element to index, the real problem starts when we have a sublist and its element has to be indexed. Let’s discuss certain ways in which this can be performed.

Method #1 : Using index() + list comprehension
This method solves this problem in 2 parts, for the first part it generates a new list and then it performs indexing on it.




# Python3 code to demonstrate

# indexing of sublist

# using list comprehension + index()

# initializing test list

test_list = [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]

# printing original list

print("The original list : " + str(test_list))

# using list comprehension + index()

# indexing of sublist

res = [ele for i, ele in test_list].index('For')

# print result

print("Index of nested element is : " + str(res))

Output : The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']] Index of nested element is : 1

Method #2 : Using next() + enumerate()
This problem can be solved in an efficient manner using the combination of the above functions. The next function checks for the elements and enumerate functions separates the nested list elements.




# Python3 code to demonstrate

# indexing of sublist

# using enumerate() + next()

# initializing test list

test_list = [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]

# printing original list

print("The original list : " + str(test_list))

# using enumerate() + next()

# indexing of sublist

res = next((i for i, (j, ele) in enumerate(test_list) if ele == 'For'), None)

# print result

print("Index of nested element is : " + str(res))

Output : The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']] Index of nested element is : 1

How do you find the index of an element in a nested list?




Article Tags :

Python

Python Programs

Python list-programs

What is Python Nested List?

A list can contain any sort object, even another list (sublist), which in turn can contain sublists themselves, and so on. This is known as nested list.

You can use them to arrange data into hierarchical structures.

3 Built in List Functions

To find the length of the list or the number of elements in a list, len( ) is used.

If the list consists of all integer elements then min( ) and max( ) gives the minimum and maximum value in the list. Similarly sum is the sum

num = [1,2,3,4,5,6,7,8,9] print("min =",min(num)," max =",max(num)," total =",sum(num))

min = 1 max = 9 total = 45

Lists can be concatenated by adding, ‘+’ them. The resultant list will contain all the elements of the lists that were added. The resultant list will not be a nested list.

There might arise a requirement where you need to check if a particular element is there in a predefined list. Consider the below list.

names = ['Earth','Air','Fire','Water']

To check if ‘Fire’ and ‘Space’ is present in the list names, a conventional approach would be to use a for loop and iterate over the list and use the if condition. But in python you can use ‘a in b’ concept which would return ‘True’ if a is present in b and ‘False’ if not.

In a list with string elements, max( ) and min( ) are still applicable and return the first/last element in lexicographical order.

mlist = ['bzaa', 'acs', 'ac', 'az', 'zg', 'k'] print("max =",max(mlist)) print("min =",min(mlist))

When comparing ASCII values, the system proceeds character by character, starting with the first character. If there is exactly one element whose first character has the lowest / highest ASCII value, min/max outputs this element. In the above example, this is the case for the “maximum string” ‘zg’. For the “minimum string” there are several elements with an ‘a’ at the first place, so the min function compares the second places here. With ‘acs’ and ‘ac’ there are two possible candidates for the “minimal string”. If a string “stops”, it is automatically smaller than a string that continues, i.e. ‘ac’ is smaller than ‘acs’. This procedure is the same as the alphabetical sorting.

However, if you write numbers as strings and want to output the minimum or maximum, they are also compared character by character. Thereby it is ignored how many characters the number contains, i.e. whether it is written in tens, hundreds, thousands,… range. This explains strange “errors”, as the following example shows:

nlist = ['5', '10', '93', '94', '1000'] print("max =",max(nlist)) print('min =',min(nlist))

If you want to find the max( ) string element based on the length of the string then another parameter key can be used to specify the function to use for generating the value on which to sort. Hence finding the longest and shortest string in mlist can be done using the len function:

print('longest =',max(mlist, key=len)) print('shortest =',min(mlist, key=len))

longest = bzaa shortest = k

Any other built-in or user defined function can be used.

A string can be converted into a list by using the list() function, or more usefully using the split() method, which breaks strings up based on spaces.

print(list('hello world !'),'Hello World !!'.split())

['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', '!'] ['Hello', 'World', '!!']

append( ) is used to add a single element at the end of the list.

lst = [1,1,4,8,7] lst.append(1) lst

Appending multiple elements to a list would create a sublist. To avoid a nested list then the extend( ) function can be used.

lst.extend([10,11,12]) lst

[1, 1, 4, 8, 7, 1, 10, 11, 12]

count( ) is used to count the number of a particular element that is present in the list.

index( ) is used to find the index value of a particular element. Note that if there are multiple elements of the same value then the first index value of that element is returned.

lst.index(1), lst.index(11)

insert(x,y) is used to insert a element y at a specified index value x. append( ) function made it only possible to insert at the end.

[1, 1, 4, 8, 7, 'name', 1, 10, 11, 12]

insert(x,y) inserts but does not replace elements. If you want to replace an element with another element you simply assign the value to that particular index.

[1, 1, 4, 8, 7, 'Python', 1, 10, 11, 12]

pop( ) removes and returns the last element in the list.

The Index value can be specified to pop a ceratin element corresponding to that index value.

pop( ) is used to remove an element based on it’s index value. One can also remove element by specifying the element itself using the remove( ) function.

Alternative to remove function but with using index value is del. It is basically the same as pop without returning it.

The entire elements present in the list can be reversed by using the reverse() function.

Note that in case of a nested list an element like [5,4,2,8] is treated as a single element of the parent list lst. Thus the elements inside the nested list is not reversed.

lst2 = [['a','b'], [5,4,2,8], [1], []] lst2.reverse() lst2

[[], [1], [5, 4, 2, 8], ['a', 'b']]

Python offers built in operation sort( ) to arrange the elements in ascending order. Alternatively sorted() can be used to construct a copy of the list in sorted order without changing the original list.

For descending order use the parameter “reverse” and set it to “True”.

lst.sort(reverse=True) lst

Similarly for lists containing string elements, sort( ) would sort the elements based on it’s ASCII value in ascending and by specifying reverse=True in descending.

['Air', 'Earth', 'Fire', 'Water']

names.sort(reverse=True) names

['Water', 'Fire', 'Earth', 'Air']

To sort based on length key=len should be specified as shown.

['Air', 'Fire', 'Water', 'Earth']

print(sorted(names,key=len,reverse=True))

['Water', 'Earth', 'Fire', 'Air']

What’s a List of Lists?

Definition: A list of lists in Python is a list object where each list element is a list by itself. Create a list of list in Python by using the square bracket notation to create a nested list [[1, 2, 3], [4, 5, 6], [7, 8, 9]].

How do you find the index of an element in a nested list?

Do you want to develop the skills of a well-rounded Python professional—while getting paid in the process? Become a Python freelancer and order your book Leaving the Rat Race with Python on Amazon (Kindle/Print)!

How do you find the index of an element in a nested list?

Memory Analysis

It’s important that you understand that a list is only a series of references to memory locations. By playing with the code visualizer, you’ll gain a deeper understanding of how Python works at its core:

Simply click the “Next” button to see how each line of code unfolds.

Create a List of Lists in Python

Create a list of lists by using the square bracket notation. For example, to create a list of lists of integer values, use [[1, 2], [3, 4]]. Each list element of the outer list is a nested list itself.

Convert List of Lists to One List

Say, you want to convert a list of lists [[1, 2], [3, 4]] into a single list [1, 2, 3, 4]. How to achieve this? There are different options:

  • List comprehension [x for l in lst for x in l] assuming you have a list of lists lst.
  • Unpacking [*lst[0], *lst[1]] assuming you have a list of two lists lst.
  • Using the extend() method of Python lists to extend all lists in the list of lists.

Find examples of all three methods in the following code snippet:

lst = [[1, 2], [3, 4]] # Method 1: List Comprehension flat_1 = [x for l in lst for x in l] # Method 2: Unpacking flat_2 = [*lst[0], *lst[1]] # Method 3: Extend Method flat_3 = [] for l in lst: flat_3.extend(l) ## Check results: print(flat_1) # [1, 2, 3, 4] print(flat_2) # [1, 2, 3, 4] print(flat_3) # [1, 2, 3, 4]

Due its simplicity and efficiency, the first list comprehension method is superior to the other two methods.