Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – len function not working as expected, and giving me the error "TypeError: object of type 'int' has no len()"

While studying linked lists from – https://composingprograms.com/pages/23-sequences.html#linked-lists

empty ='empty'
four = [1, [2, [3, [4, 'empty']]]]
x = [1,2];

def is_link(s):
    """s is a linked list if it is empty or a (first, rest) pair."""
    return s == empty or (len(s) == 2 and is_link(s[1]))

print(is_link(four))
print(is_link(x))

The program recognizes four as a linked list, But when i plug in x it returns an error instead of returning "False".

If i change value of x to just [1] or [1,2,3] it returns as expected, but if i enter a normal list [1,2] with 2 values i run into this error. .Why is this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Look at the executions, on your condition len(s) == 2 this only satisfies [1, 2] so it checks for the next one is_link(s[1]) which raises an error because it’s a check length of integer in next iteration.

In [24]: print(is_link([1]))
[1]
False

In [25]: print(is_link([1, 2, 3]))
[1, 2, 3]
False

In [26]: print(is_link([1, 2]))
[1, 2]
2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [26], in <module>
----> 1 print(is_link([1, 2]))

Input In [20], in is_link(s)
      2 print(s)
      3 """s is a linked list if it is empty or a (first, rest) pair."""
----> 4 return s == empty or (len(s) == 2 and is_link(s[1]))

Input In [20], in is_link(s)
      2 print(s)
      3 """s is a linked list if it is empty or a (first, rest) pair."""
----> 4 return s == empty or (len(s) == 2 and is_link(s[1]))

TypeError: object of type 'int' has no len()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading