tags:

views:

155

answers:

3

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?

+2  A: 

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.

nosklo
+5  A: 

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)
KennyTM
That makes no sense, and wouldn't cause the problem. A parameter or variable can have any name, even one that shadows a builtin, and it won't magically refer to the builtin instead of the actual value.
Devin Jeanpierre
Perhaps it made more sense after the edit, but I think KennyTM is saying also be sure not to call the method passing in something called "list" either (unless it is also overwritten to mean something else).I think most of us here would agree that using the same name as a builtin is a surefire way to run into problems and confusion when you're learning a language. Coders should avoid this, as a best practice, unless they truly intend to override/shadow a builtin (which is rare).
Matthew
+5  A: 

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.

SilentGhost