Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the fastest way to locate a list element within a list in python?

The list is similar to this:

[["12", "stuA", "stuB"], ["51", "stuC", "stuD"], ..., ["3234", "moreStuff", "andMore"]]

Now I need to locate an item (get index) only by its first value (e.g. "332"). Is there any better way to do this, apart from iterating from the first one to compare with each value?

Code:

index = 0
for item in thelist:
    if item[0] == "332":
         print index

    index = index + 1
like image 633
Shane Avatar asked Dec 19 '13 13:12

Shane


People also ask

How do you access a list within a list in Python?

We can access the contents of a list using the list index. In a flat list or 1-d list, we can directly access the list elements using the index of the elements. For instance, if we want to use positive values as the index for the list elements, we can access the 1st item of the list using index 0 as shown below.

How do you find the location of an element in a list in Python?

To facilitate this, Python has an inbuilt function called index(). This function takes in the element as an argument and returns the index. By using this function we are able to find the index of an element in a list in Python.

Is there a find method for lists in Python?

I was trying to write an answer to this question and was quite surprised to find out that there is no find method for lists, lists have only the index method (strings have find and index).


2 Answers

No. Without iterating you cannot find it, unless the list is already sorted. You can improve your code like this, with enumerate and list comprehension.

[index for index, item in enumerate(thelist) if item[0] == "332"]

This will give the indices of all the elements where the first element is 332.

If you know that 332 occurs only once, you can do this

def getIndex():
    for index, item in enumerate(thelist):
       if item[0] == "332":
          return index
like image 94
thefourtheye Avatar answered Oct 31 '22 01:10

thefourtheye


No-one's mentioned this yet, so I will - if you need to find an item by its value quickly (and presumably more than just once), you should change the data structure you use to be one that supports the kind of access you need. Lists support fast access by index, but not by item value. If you stored the information in a dict keyed by the first element in the lists, you would be able to find rows very quickly by that first value:

# Make a dict from the list of lists:
itemLookup = {item[0]: item for item in theList}

itemLookup["51"] # -> ["51", "stuC", "stuD"]

So the brief answer is no (although there is a quick-ish way using bisection if the list is sorted), the longer answer is use a dictionary if you want fast lookup.

like image 24
babbageclunk Avatar answered Oct 31 '22 02:10

babbageclunk