PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def custom_len(item):
"""Custom len() function: if called on a list of strings, returns a list with the length of each string, instead of the length of the list itself."""
# checks if item is of type str
if isinstance(item, str):
return len(item)
# checks if item is of type list
elif isinstance(item, list):
# calls the function itself from inside a list comprehension
return [custom_len(each) for each in item]
# other types will not work
else:
raise TypeError
print("test 1:", custom_len("hello"))
print("test 2:", custom_len(["hello", "solo", "learn"]))
print("test 3:", custom_len([["one", "two"], ["three", "four"]]))
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run