Finding the index of an item in a list
>>> ["foo", "bar", "baz"].index("bar")
1
Reference: Data Structures > More on Lists
Caveats follow
Note that while this is perhaps the cleanest way to answer the question as asked, index
is a rather weak component of the list
API, and I can't remember the last time I used it in anger. It's been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. Some caveats about list.index
follow. It is probably worth initially taking a look at the documentation for it:
list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is equal to x. Raises a
ValueError
if there is no such item.The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
Linear time-complexity in list length
An index
call checks every element of the list in order, until it finds a match. If your list is long, and you don't know roughly where in the list it occurs, this search could become a bottleneck. In that case, you should consider a different data structure. Note that if you know roughly where to find the match, you can give index
a hint. For instance, in this snippet, l.index(999_999, 999_990, 1_000_000)
is roughly five orders of magnitude faster than straight l.index(999_999)
, because the former only has to search 10 entries, while the latter searches a million:
>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514
Only returns the index of the first match to its argument
A call to index
searches through the list in order until it finds a match, and stops there. If you expect to need indices of more matches, you should use a list comprehension, or generator expression.
>>> [1, 1].index(1)
0
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> next(g)
0
>>> next(g)
2
Most places where I once would have used index
, I now use a list comprehension or generator expression because they're more generalizable. So if you're considering reaching for index
, take a look at these excellent Python features.
Throws if element not present in list
A call to index
results in a ValueError
if the item's not present.
>>> [1, 1].index(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 2 is not in list
If the item might not be present in the list, you should either
- Check for it first with
item in my_list
(clean, readable approach), or - Wrap the
index
call in atry/except
block which catchesValueError
(probably faster, at least when the list to search is long, and the item is usually present.)
Getting elements of List by index in C#
You did something wrong. Because default implementation for ElementAt look like:
public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index) {
if (source == null) throw Error.ArgumentNull("source");
IList<TSource> list = source as IList<TSource>;
if (list != null) return list[index];
if (index < 0) throw Error.ArgumentOutOfRange("index");
using (IEnumerator<TSource> e = source.GetEnumerator()) {
while (true) {
if (!e.MoveNext()) throw Error.ArgumentOutOfRange("index");
if (index == 0) return e.Current;
index--;
}
}
}
For anything that implement IList it will use the same indexer as you do
Using an index to get an item
What you show, ('A','B','C','D','E')
, is not a list
, it's a tuple
(the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.
So:
thetuple = ('A','B','C','D','E')
print thetuple[0]
prints A
, and so forth.
Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0]
etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.
How can I get the index of an item in a list in a single step?
How about the List.FindIndex Method:
int index = myList.FindIndex(a => a.Prop == oProp);
This method performs a linear search; therefore, this method is an
O(n) operation, where n is Count.
If the item is not found, it will return -1
How do I get a list item by index in elm?
There is no equivalent of this in Elm.
You could of course implement it yourself.
(Note: This is not a "total" function, so it creates an exception when the index is out of range).
infixl 9 !!
(!!) : [a] -> Int -> a
xs !! n = head (drop n xs)
A better way would be to define a total function, using the Maybe data type.
infixl 9 !!
(!!) : [a] -> Int -> Maybe a
xs !! n =
if | n < 0 -> Nothing
| otherwise -> case (xs,n) of
([],_) -> Nothing
(x::xs,0) -> Just x
(_::xs,n) -> xs !! (n-1)
Get value of certain index in list C#
I'm not sure what exactly do You need, but if You want to get value of certain index in list C# You can just do this using square brackets syntax
:
List<something> list = GetListOfSomething();
var someItem = list[yourIndex];
You can do this because List<T>
implements IList<T>
interface which defines this indexer:
object this[int index] { get; set; }
Also You can use Linq to Objects
to query your List.
Hope this helps.
Get the index of item in a list given its property
As it's an ObservableCollection
, you can try this
int index = MyList.IndexOf(MyList.Where(p => p.Name == "ComTruise").FirstOrDefault());
It will return -1
if "ComTruise" doesn't exist in your collection.
As mentioned in the comments, this performs two searches. You can optimize it with a for loop.
int index = -1;
for(int i = 0; i < MyList.Count; i++)
{
//case insensitive search
if(String.Equals(MyList[i].Name, "ComTruise", StringComparison.OrdinalIgnoreCase))
{
index = i;
break;
}
}
Access multiple elements of list knowing their index
You can use operator.itemgetter
:
from operator import itemgetter
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)
Or you can use numpy:
import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]
But really, your current solution is fine. It's probably the neatest out of all of them.
Cannot get an index of a list item
The problem is that the type of variable pick
is a list
.
You need to pass an int
to the index
command:
In [314]: list1.index(pick[0])
Out[314]: 4
Related Topics
Checking If a Bit Is Set or Not
Linq Ring: Any() VS Contains() for Huge Collections
Invalid Attempt to Read When No Data Is Present
Clipboard.Gettext Returns Null (Empty String)
Is String.Contains() Faster Than String.Indexof()
Dotnet Core System.Text.JSON Unescape Unicode String
Xml.Loaddata - Data at the Root Level Is Invalid. Line 1, Position 1
Timeouts with Long Running ASP.NET MVC Core Controller Httppost Method
Wpf: How to Dynamically Add Controls in Dynamically Created Wpf Window
Access a Remote Directory from C#
How to Compare (Directory) Paths in C#
How to Invoke an Extension Method Using Reflection
The ':' Character, Hexadecimal Value 0X3A, Cannot Be Included in a Name
How to Get All Instances of All Loaded Types That Implement a Given Interface
Can't Add Script Component Because the Script Class Cannot Be Found
Filenotfoundexception in Applicationsettingsbase
C# How to Translate Virtual Keycode to Char
How to Fix "Referenced Assembly Does Not Have a Strong Name" Error