TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to PYTHON

Python Index and Count (Search List)

Use the index and count methods to search lists. A benchmark of index is provided.
Index. This searches lists. We pass it an argument that matches a value in the list. It returns the index where that value is found. If no value is found, it throws an error.List
And with count, we count the matching elements in a list. Like index() this loops through and tests each element in a linear way. List provides no rindex method.
Index example. This example shows how the index() method searches a list. If no value is found, we get an Error. We can handle this in a try-except block (but this is not ideal).Error

Tip: For programs where you need more control, consider using a for-loop instead of index().

for

Info: With a for-loop, we can more elegantly handle cases where the value is not found. This avoids the ValueError.

Python program that uses index # Input list. values = ["uno", "dos", "tres", "cuatro"] # Locate string. n = values.index("dos") print(n, values[n]) # Locate another string. n = values.index("tres") print(n, values[n]) # Handle nonexistent string. try: n = values.index("?") # Not reached. print(n) except: # Value not found. print("Not found") Output 1 dos 2 tres Not found
Count. This method does not return the number of elements in the list. Instead it counts a specific element. As an argument, pass the value of the element we wish to count.

Note: Internally count() loops through all the elements and keeps track of the count. It then returns this value.

Python program that uses count names = ['a', 'a', 'b', 'c', 'a'] # Count the letter a. value = names.count('a') print(value) Output 3
Benchmark, index. What is the fastest way to search a list? Given that searching a list is common done, learning the best way to do this is beneficial.

Version 1: We test the index() method. Index() raises an exception if no match is found.

Version 2: In this version of the code we use a for-loop with a range. This code does not raise an exception.

Result: In this test, the index method is far faster than the for-loop that tests each string element.

So: Index() is likely optimized at a low level in Python. I suggest you prefer index() for list searching.

Python program that times list searching import time values = ["Augustus", "Tiberius", "Caligula", "Claudius"] print(time.time()) # Version 1: index. i = 0 while i < 10000000: v = values.index("Caligula") i += 1 print(time.time()) # Version 2: for-range. i = 0 while i < 10000000: v = 0 for n in range(0, len(values)): if values[n] == "Caligula": v = n break i += 1 print(time.time()) Output 1362429980.178 1362429984.018 index() = 3.84 s 1362429994.569 for = 10.55 s
Performance, count. Consider the count() method. If we were to keep track of the items added to the list as we add them, we could compute counts without a loop. This would be faster.
A review. With index and count, we have declarative (function-based) ways of testing the elements of a list. We can search for matching elements (and get an index, or the sum of matches).
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf