Python lists provide index and count methods, both of which can be used to find elements.
The index () method is used to find the position (that is, the index) of an element in the list. If the element does not exist, it will cause a ValueError error, so it is best to use the count () method to judge it before searching.
The syntax of index () is:
listname.index (obj, start, end)
Among them, listname represents the name of the list, obj represents the element to find, start represents the starting position, and end represents the ending position.
The start and end parameters are used to specify the search range:
The index method returns the index value in the list where the element is located.
Example of index method:
no = [32, 56, 79, 45, 2, 100, -3, -34.1, -888] #Retrieve all elements in the list print (no.index (2)) #Retrieve elements between 3 ~ 7 print (no.index (100, 3, 7)) #Retrieve elements after 4 print (no.index (2, 4)) #Retrieve a non-existing element print (no.index (66))
The output is:
4
5
4
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
[ipython-input-94-782b4504085f] in [module]
7 print (no.index (2, 4))
8 #Retrieve a non-existing element
----> 9 print (no.index (66))
ValueError: 66 is not in list
The count method is used to count the number of times an element appears in the list. The basic syntax is:
listname.count (obj)
Among them, listname represents the name of the list, and obj represents the elements to be counted.
If count returns 0, it means that the element does not exist in the list, so count method can also be used to determine whether an element in the list exists.
count method usage example:
nums = [23, 39, 67, 8, 39, 99, 7, -22.3, 39] #Statistic element occurrences print ("39 occured% d times"% nums.count (39)) #Determine if an element exists if nums.count (99): print ("99 elements exist in the list") else: print ("99 element does not exist in the list")
The output is:
39 occured 3 times
99 elements exist in the list
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises