difference between find and index
I am new to python and cannot quite understand the difference between find and index.
They always return the same result. Thanks!!
3 Answers 3
str.find returns -1 when it does not find the substring.
While str.index raises ValueError :
Both the functions behave the same way if a sub-string is found.
Also find is only available for strings where as index is available for lists, tuples and strings
@falsetru provided an explanation about the difference between functions, I did a performance test between them.
![]()
-
The Overflow Blog
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.6.8.43486
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Чем отличается index от find python
The Python List is a general data structure widely used in Python programs. They are found in other languages, often referred to as dynamic arrays. They are both mutable and a sequence data type that allows them to be indexed and sliced. The list can contain different types of objects, including other list objects.
# List methods and supported operators
Starting with a given list a :
Note that the append() method only appends one new element to the end of the list. If you append a list to another list, the list that you append becomes a single element at the end of the first list.
Lists can also be concatenated with the + operator. Note that this does not modify any of the original lists:
Lists can also be reversed when sorted using the reverse=True flag in the sort() method.
If you want to sort by attributes of items, you can use the key keyword argument:
In case of list of dicts the concept is the same:
Sort by sub dict :
Better way to sort using attrgetter and itemgetter
Lists can also be sorted using attrgetter and itemgetter functions from the operator module. These can help improve readability and reusability. Here are some examples,
itemgetter can also be given an index. This is helpful if you want to sort based on indices of a tuple.
Use the attrgetter if you want to sort by attributes of an object,
Take care doing this if your list contains references to objects (eg a list of lists), see Common Pitfalls — List multiplication and common references
If you want to create a copy of the list you have below options. You can slice it:
You can use the built in list() function:
You can use generic copy.copy():
This is a little slower than list() because it has to find out the datatype of old_list first. If the list contains objects and you want to copy them as well, use generic copy.deepcopy():
Obviously the slowest and most memory-needing method, but sometimes unavoidable.
copy() – Returns a shallow copy of the list
# Accessing list values
Python lists are zero-indexed, and act like arrays in other languages.
Attempting to access an index outside the bounds of the list will raise an IndexError .
Negative indices are interpreted as counting from the end of the list.
This is functionally equivalent to
Lists allow to use slice notation as lst[start:end:step] . The output of the slice notation is a new list containing elements from index start to end-1 . If options are omitted start defaults to beginning of list, end to end of list and step to 1:
With this in mind, you can print a reversed version of the list by calling
When using step lengths of negative amounts, the starting index has to be greater than the ending index otherwise the result will be an empty list.
Using negative step indices are equivalent to the following code:
The indices used are 1 less than those used in negative indexing and are reversed.
Advanced slicing
When lists are sliced the __getitem__() method of the list object is called, with a slice object. Python has a builtin slice method to generate slice objects. We can use this to store a slice and reuse it later like so,
This can be of great use by providing slicing functionality to our objects by overriding __getitem__ in our class.
# Checking if list is empty
The emptiness of a list is associated to the boolean False , so you don’t have to check len(lst) == 0 , but just lst or not lst
# Iterating over a list
Python supports using a for loop directly on a list:
You can also get the position of each item at the same time:
The other way of iterating a list based on the index value:
Note that changing items in a list while iterating on it may have unexpected results:
In this last example, we deleted the first item at the first iteration, but that caused bar to be skipped.
# Checking whether an item is in a list
Python makes it very simple to check whether an item is in a list. Simply use the in operator.
Note: the in operator on sets is asymptotically faster than on lists. If you need to use it many times on potentially large lists, you may want to convert your list to a set , and test the presence of elements on the set .
# Any and All
You can use all() to determine if all the values in an iterable evaluate to True
Likewise, any() determines if one or more values in an iterable evaluate to True
While this example uses a list, it is important to note these built-ins work with any iterable, including generators.
# Length of a list
Use len() to get the one-dimensional length of a list.
len() also works on strings, dictionaries, and other data structures similar to lists.
Note that len() is a built-in function, not a method of a list object.
Also note that the cost of len() is O(1) , meaning it will take the same amount of time to get the length of a list regardless of its length.
# Reversing list elements
You can use the reversed function which returns an iterator to the reversed list:
Note that the list "numbers" remains unchanged by this operation, and remains in the same order it was originally.
To reverse in place, you can also use the reverse method
You can also reverse a list (actually obtaining a copy, the original list is unaffected) by using the slicing syntax, setting the third argument (the step) as -1:
# Concatenate and Merge lists
If the lists have different lengths then the result will include only as many elements as the shortest one:
For padding lists of unequal length to the longest one with None s use itertools.zip_longest ( itertools.izip_longest in Python 2)
# Remove duplicate values in list
Removing duplicate values in a list can be done by converting the list to a set (that is an unordered collection of distinct objects). If a list data structure is needed, then the set can be converted back to a list using the function list() :
Note that by converting a list to a set the original ordering is lost.
To preserve the order of the list one can use an OrderedDict
# Comparison of lists
It’s possible to compare lists and other sequences lexicographically using comparison operators. Both operands must be of the same type.
If one of the lists is contained at the start of the other, the shortest list wins.
# Accessing values in nested list
Starting with a three-dimensional list:
Accessing items in the list:
Performing support operations:
Using nested for loops to print the list:
Note that this operation can be used in a list comprehension or even as a generator to produce efficiencies, e.g.:
Not all items in the outer lists have to be lists themselves:
Another way to use nested for loops. The other way is better but I’ve needed to use this on occasion:
Using slices in nested list:
# Initializing a List to a Fixed Number of Elements
For immutable elements (e.g. None , string literals etc.):
For mutable elements, the same construct will result in all elements of the list referring to the same object, for example, for a set:
Instead, to initialize the list with a fixed number of different mutable objects, use:
# Syntax
- [value, value, . ]
- list([iterable])
# Remarks
list is a particular type of iterable, but it is not the only one that exists in Python. Sometimes it will be better to use set
list is the name given in Python to dynamic arrays (similar to vector<void*> from C++ or Java’s ArrayList<Object> ). It is not a linked-list.
Accessing elements is done in constant time and is very fast. Appending elements to the end of the list is amortized constant time, but once in a while it might involve allocation and copying of the whole list .
Difference between find() and index() in Python
Hey, guys today we are going to learn the difference between find() and index() in Python. Both these string methods are very similar but have few differences. Before starting with the differences let’s discuss find() and index() methods in Python.
find() method in Python
find() is used to determine the position at which a substring is first found in a string. In other words, find() returns the index of the first occurrence of a substring in a string. find() takes 3 parameters: substring that is to be searched, index of start and index of the end(The substring is searched between the start and end indexes of the string) out of which indexes of start and end are optional.
If the substring is not found in a string find() returns -1.
Output:
index() method in Python
Just like find(), index() method determines the position at which a substring is first found in a string. In the same way index() takes 3 parameters: substring that is to be searched, index of start and index of the end(The substring is searched between the start and end indexes of the string) out of which indexes of start and end are optional.
If the substring is not found in a string index() raises ValueError exception.
find и index в Python
Cтроки являются списками символов по которым можно искать совпадения. Методы find и index В Python позволяют эти совпадения находить.
Методы find и index в Python
Синтаксис вызова метода:
wheretosearch — строка, по которой выполняется поиск
template — строка, совпадение с которой ищем
Метод find вернет индекс первого символа при обнаружении совпадения, если совпадения нет '-1'.
Метод index отличается только тем, что при отсутствии совпадения вместо единицы вызывает ValueError.
>> wheretosearch=»some string with template text in it»
Позиция, на которой обнаружено вхождение — 26, первый символ строки имеет индекс 0.
Далее попробуем выполнить поиск по значению, которого в строке изначально нет.
Определим новую переменную
-1
В результате получает -1.
Таким же образом для метода index
ValueError далее можно обрабатывать при помощи конструкции try — exept
Читайте про метод split, он используется для выделения в строках текста нужного содержимого относительно разделителя. Это во многом аналог awk в bash.