Reputation: 8067
The problem:
Write a loop that traverses:
['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
and prints the length of each element.
I have tried as my solution:
list = ['spam!', 1,['Brie', 'Roquefort', 'Pol le Veq'], [1,2,3]]
element = 0
for i in list:
print len(list[element])
element += 1
But it receives this error: TypeError: object of type 'int' has no len()
Upvotes: 1
Views: 38865
Reputation: 1
def listlen(lists1):
"""
return length of each element in a list
"""
import numpy
newlist = []
for item in lists1:
if type(item) in [list,str,numpy.ndarray]:
newlist.append(len(item))
else:
newlist.append(len([item]))
return newlist
# example usage -
listlen(["somestring", 5, [1,2,3]] )
[10, 1, 3]
Upvotes: 0
Reputation: 67
Can use map and __ len __ to check does it will raise error when use len(), e.g.
myList = ['spam!', 1,['Brie', 'Roquefort', 'Pol le Veq'], [1,2,3]]
myList_filter = list(filter(lambda x: hasattr(x, "__len__"), myList))
myList_len = list(map(len, myList_filter))
print(myList_len) # [5, 1, 3, 3]
error_type = [entry for entry in myList if entry not in myList_filter]
print("{0} has no defined length".format(error_type)) # [1] has no defined length
Upvotes: 1
Reputation: 59
I was thinking on your question and I thought that you maybe were new in Python as me, for me everything was solved in R. The solution that I found is to set all the elements in the list... into a list 'element' so the last code can run over all the lists in the list:
for k in range(len(items)):
if type(items[k])!= list:
items[k]=[items[k]]
items
[len(i) for i in items]
>>[1, 1, 3, 3]
Upvotes: 1
Reputation: 4419
The only possible solution is change the int
type to str
and vice-versa.
If it is only a exercise, it should be not a problem.
Upvotes: 0
Reputation: 41
First of all, using that element variable as an index for accessing your list items is redundant. When writing a for loop in python, you are iterating through each item in the list such that, on iteration 1:
for item in [1, [1,2,3]]:
# item = 1
...
And on the next iteration: for item in [1, [1,2,3]]: # item = [1, 2, 3] ...
The next problem is that you have an item in that list with no defined length. I don't know what you want to do with that, but a possible solution is this, which will print the length of the item (in digits) if the item is an integer:
items = ['spam!', 1,['Brie', 'Roquefort', 'Pol le Veq'], [1,2,3]]
for item in items:
if isinstance(item, int):
print(len(str(item)))
else:
print(len(item))
Upvotes: 1
Reputation: 3826
As others have pointed out, the number 1 (second entry of the main list) does not have a defined length. But you still can catch the exception and print out something if something like this is the case, e.g.
myList = ['spam!', 1,['Brie', 'Roquefort', 'Pol le Veq'], [1,2,3]]
for entry in myList:
try:
l = len(entry)
print "Length of", entry, "is", l
except:
print "Element", entry, "has no defined length"
Upvotes: 1