From this site, it says that list.index() is a linear search through the list.
And it also seems like in is also linear.
Is there any advantage to using one over the other?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you want to compare different python approaches, such as the
inoperator versus.index(), use thetimeitmodule to test the speed differences. Python data type complexities are documented on http://wiki.python.org/moin/TimeComplexity.Do note that there is a big difference between
inand.index(); the first one returns a boolean, the latter the index of the found item (an integer) or it’ll raise an exception. It thus is (slightly) slower for the average case:If you need to optimize for membership testing, use a
set()instead: