Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cant pass keyword argument to list.index() method?

I was checking the documentation of list.index() method in python, what I saw is :

>>> help(list().index)
Help on built-in function index:

index(value, start=0, stop=9223372036854775807, /) method of builtins.list
instance
Return first index of value.

Raises ValueError if the value is not present.

When I ran the code below gave me some error.

>>> l=[1,2,3,43,45,5,6,6]
>>> l.index(43,start=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: index() takes no keyword arguments
like image 673
Dheeraj Singh Avatar asked Nov 01 '25 05:11

Dheeraj Singh


2 Answers

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.

like image 175
Nir Alfasi Avatar answered Nov 02 '25 19:11

Nir Alfasi


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.

like image 45
ShadowRanger Avatar answered Nov 02 '25 18:11

ShadowRanger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!