Eric Wilson
Eric Wilson

Reputation: 59355

Why can't I find `len(list)` in Python?

I'm new to Python. I have a method that begins:

def foo(self, list):
    length = len(list)

I've called len() successfully in other cases, but here I get:

TypeError: object of type 'type' has no len()

How do I convince Python that this object passed in is a list? What am I missing?

Upvotes: 2

Views: 1607

Answers (3)

kennytm
kennytm

Reputation: 523274

Because list is the name of the list type.

Use a different name.

def foo(self, lst):
    length = len(lst)

And make sure you didn't call foo like this:

Foo.foo(list)

Upvotes: 5

SilentGhost
SilentGhost

Reputation: 319601

you're shadowing built-in. The value that you're passing to foo method is not a list object, but rather a list type, that doesn't have any length.

Upvotes: 5

nosklo
nosklo

Reputation: 222852

Seems like you're calling type() on list which is a type itself. Don't use the name list for your lists because it is a already a built-in type. use L or mylist or whatever and it should work.

Upvotes: 2

Related Questions