How do you know the index of an element that in the sub list

find index of element in nested list python
python list index
python find index of all occurrences in list
python find index of first occurrence in list
python find position in list
accessing list of lists python
index of all element in list python
python select list elements by index

How do you know the index of an element that is in a sub list? A similar question was asked here for lists without nesting

Like so:

L=[[1, 2, 3], [4, 5, 6]]

What I want to be as output when the element is 3:


a = 3

print([(i,j) for i,x in enumerate(L) if a in x for j,b in enumerate(x) if b == a])
#[(0, 2), (2, 1), (2, 4)]

using list comprehension you can dig and return all the sub values. If you need to go deeper just keep chaining the list comprehension or write a function to do it.

Python, The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']] Index of nested element is : 1. Method #2 : Using manjeet_04. Check out this Author's contributed articles. index() is an inbuilt function in Python, which searches for given element from start of the list and returns the lowest index where the element appears. Syntax : list_name.index(element, start, end) Parameters : element - The element whose lowest index will be returned.

Try this:

def get_sublist_index(lists, item):
    for sublist in lists:
        if item in sublist:
            return lists.index(sublist), sublist.index(item)

>>> L=[[1,2,3],[4,5,6]]
>>> get_sublist_index(L, 3)
(0, 2)

Or to get every item:

def get_sublist_index(lists, item):
    for sublist in lists:
        if item in sublist:
            yield lists.index(sublist), sublist.index(item)

Making a generator:

>>> L=[[1,2,3],[4,3,6]]
>>> get_sublist_index(L, 3)
<generator object get_sublist_index at 0x1056c5e08>
>>> [i for i in get_sublist_index(L, 3)]
[(0, 2), (1, 1)]

Or if you don't want a generator:

def get_sublist_index(lists, item):
    outList = []
    for sublist in lists:
        if item in sublist:
            outList.append((lists.index(sublist), sublist.index(item)))
    return outList

>>> get_sublist_index(L, 3)
[(0, 2), (1, 1)]

Python: How to find all indexes of an item in a List? –, method to find the first index of a given element in list or a sub list i.e. occurrences of an item in the list and we want to know their indexes ? One of the big differences between the first_index solutions and the manual solutions is that the first_index function will return the index immediately when it was found, while grep will go over the list of all the planets before returning the result. Even if the first element already matched.

Perhaps something like this:

def find_sublist(outer, what):
    for i, lst in enumerate(outer):
            return i, lst.index(what)
        except ValueError:

Actually, output = [0][2] will throw an exception. Not sure what you mean by this. Do you want a tuple of two elements? I will assume you do.

You could alternatively use something more elegant, like

In [8]: [(i, sublist.index(3)) for i, sublist in enumerate(L) if 3 in sublist]
Out[8]: [(0, 2)]

In [9]: [(i, sublist.index(4)) for i, sublist in enumerate(L) if 4 in sublist]
Out[9]: [(1, 0)]

Python List index(), It is common to use a loop variable as a list index. As usual, the sublist selected by slice contains all the elements up to, but not including, the second index. we know that a and b will refer to a string object with the letters "banana". But we  By including only the index number before the colon and leaving the second index number out of the syntax, the substring will go from the character of the index number called to the end of the string. You can also use negative index numbers to slice a string.

"One-line" solution using numpy.where and numpy.transpose methods(the initial input array was extended to cover a complex case):

import numpy as np

L = [[1,2,3],[4,3,6]]  # 3 occurs twice
output = np.transpose(np.where(np.array(L) == 3))


The output:

 [[0 2]
  [1 1]]

11. Lists, The index() method searches an element in the list and returns its position/index. First, this tutorial will introduce you to lists, and then you will see  Finding an element in a list is a very common task we come across as developers. In this quick tutorial, we'll cover different ways we can do this with Java. Learn several algorithms for checking whether a list is sorted in Java. In this quick tutorial, we'll investigate how can we initialize a List using one-liners.

You should always count on enumerate for tasks that require indices and sequences:

def find_index(l, val=3):
    # res holds results
    res = []
    # Go through every sublist in l 
    # index1 indicates which sublist we check
    for index1, sublist in enumerate(l):
        # Go through every item in sublist 
        # index2 indicates which item we check
        for index2, item in enumerate(sublist):
            # append to result if we find a match
            if item == val:
                res.append([index1, index2])
    return res

With a sample list:

L = [[1, 2, 3], [4, 5, 6, 4, 3], [3, 3, 3]]

this returns:

[[0, 2], [1, 4], [2, 0], [2, 1], [2, 2]]

Python List Index(), The user can access elements by their integer index (position in the list), and in a list is typically preferable to indexing through it if the caller does not know the Parameters: fromIndex - low endpoint (inclusive) of the subList: toIndex - high  This is the last index in a list. This will happened if you try to use an index that is out of range for a list. This function return the length of a list. When the * operator's left operand is a list and its right operand is and integer, the operator becomes this.

List (Java SE 11 & JDK 11 ), Returns the index of the first occurrence of the specified element in this list, or -1 (This is useful in determining the length of the list only if the caller knows that the and all of the algorithms in the Collections class can be applied to a subList​. Varun March 2, 2018 Python : How to Insert an element at specific index in List ? In this article we will discuss how to insert an element in list at specific position. In python list provides a member function insert () i.e. It accepts a position and an element and inserts the element at given position in the list.

ArrayList (Java Platform SE 8 ), Nested lists are list objects where the elements in the lists can be lists themselves​. Using this figure, you can realize that the first index looks up an element in the outer list, This is natural code when we know that table is a list of [C, F] lists. When there is no public data on the element in its pure form, price of a compound is used, per mass of element contained. This implicitly puts the value of compound's other constituents at zero. For elements for which their radiological properties are important, individual isotopes and isomers are listed. The price listing for radioisotopes is not exhaustive.

Nested lists, obj − This is the object to be find out. Return Value. This method returns index of the found object otherwise raise an exception indicating that value does not find. The elements are arranged in such a way that the elements get categorized according to their properties. Here we will work with only basic 8 groups (I A,II A,III A,IV A,V A,VI A,VII A and 0) .In the periodic table the first group ( except Hydrogen ) consists of strong Alkali Metals, the second group consists of Alkaline Earth Metals.

  • Can you give an example?
  • The same way you do it in that link
  • Please tell us what you mean by output = [0][2] since this is bound to throw an exception.
  • This only returns the first item you find unless that's what OP wants.
  • @MooingRawr Thanks. I'll change it.
  • find_sublist(L, 3) only gives me an output of 0 and the OP says the output should be 0, 2
  • if the list has multiple of the same in it (for example L = [[1,2,3],[4,3,6]], it returns: array([[0, 1], [2, 1]])
  • meaning that it returns [place1x, place2x], [place1y, place2y] when they want it to return [place1x, place1y], [place2x, place2y]
  • @rassar, right, I've fixed that, thanks for the hint