[Tutor] Question about list

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Apr 11 00:44:09 CEST 2006



On Mon, 10 Apr 2006, Hoffmann wrote:

> I also would like to print the length of each element
> of that list:
>
> spam! = 1 element
> 2 = 1 element
> ['Ted', 'Rock'] = 2 elements
>
> Could anyone, please, give me some hints?


The problem is slightly weird, just because you need to clarify what it 
means to take the length of a non-list.  From the examples above, it 
sounds like we'd like to define the "length" of a non-list to be one.  Is 
that right?


Can you write a function called length() that takes a thing and returns 
the "length" of that thing?

######
def length(something):
     ... ## fill me in
######


For example, we'd like to see:

     length("spam!") ==> 1
     length(2) ==> 1
     length(['Ted', 'Rock']) ==> 2

If you can define this you should be able to use this to solve your 
problem.


When you're defining length(), you may find the built-in function "type()" 
useful.  For example:

######
>>> type(5)
<type 'int'>
>>> type([1, 2, 3])
<type 'list'>
######


Good luck!



More information about the Tutor mailing list