Why I Cant Pass Keyword Argument To List.index() Method?
Solution 1:
The error message says that index
takes no keyword arguments but you are providing one with start=1
Instead of: l.index(43, start=1)
use: l.index(43, 1)
As for explanation, this could explain it:
Many of the builtin functions use only METH_VARARGS which means they don't support keyword arguments. "len" is even simpler and uses an option METH_O which means it gets a single object as an argument. This keeps the code very simple and may also make a slight difference to performance.
Solution 2:
The documentation has been poor on positional only parameters before, but on modern Python, they're improving. The key info is the seemingly out of place /
in the signature:
index(value, start=0, stop=9223372036854775807, /)
^ This is not a typo!
That means that all arguments prior to the forward slash are positional only, they can't be passed by keyword. Per the Programming FAQ for "What does the slash(/) in the parameter list of a function mean?":
A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position.
Solution 3:
index(value, start=0, stop=9223372036854775807, /)
document says here meaning of words is nothing but for what purpose you passing those arguments. for better understanding and how those arguments works, see below code example - list1 is list of 10 elements and index function is taking 3 arguments as starts and stops arguments are optional and for the purpose of slicing list, index function documentation explains it clear here -
list1 = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
for x in list1:
print(list1.index(x, 0, 5))
output
07112439416
Traceback (most recent call last):
File "main.py", line 13, in <module>
print(list1.index(x, 0, 5), x)
ValueError:25isnotin list
code starts looking for elements from start point i.e 0 and stop point i.e 5 but for loop goes ahead of 5th index and raise the value error exception
Post a Comment for "Why I Cant Pass Keyword Argument To List.index() Method?"