convert a int to a list

Tim Chase python.list at tim.thechases.com
Fri Apr 28 19:27:55 EDT 2006


> ****************************************************************
> a = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
> 
>     As an exercise, write a loop that traverses the previous list and
>     prints the length of each element. What happens if you send an
>     integer to len? 
> ****************************************************************
> 
> for i in a:
>     print len(a[i])
> 
> will not do.
> the list has str, int, list, list.
> I am expecting the output to be 1, 1, 3, 3 which are the number of
> elements of each element of a, someone might think the result should
> be 4, 3, 3 which is len(a), len(a[2]), len(a[3]) but how can I do both
> thoughts with a loop?

Well, first off, you've got a strange indexing going on 
there:  a[i] requires that the index be an integer.  You 
likely *mean*

	for thing in a:
		print len(thing)

If so, you can just wrap it in a check:

	for thing in a:
		if "__len__" in dir(thing):
			print len(thing)
		else:
			print len(str(thing))
			#print 1

or whatever sort of result you expect here.

Or you can give it a best-effort:

	for thing in a:
		try:
			print len(thing)
		except TypeError:
			print 1

and let exception-handling deal with it for you.

Just a few ideas,

-tkc









More information about the Python-list mailing list