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
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.
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.
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).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With