Home > other >  "int has no lenght" when trying to print a list on different lines
"int has no lenght" when trying to print a list on different lines

Time:10-16

error "line 11, in sort if len(num) > 1: TypeError: 'int' has no length" is shown when trying to run this code :

from sys import stdin, stdout

def readln():
  return stdin.readline().rstrip()

def outln(n):
  stdout.write(str(n))
  stdout.write("\n")

def sort(num):
  menor = []
  igual = []
  maior = []
  if len(num) > 1:
    pivot = num[0]
    for x in num:
      if x < pivot:
        menor.append(x)
      elif x == pivot:
        igual.append(x)
      elif x > pivot:
        maior.append(x)
    return sort(menor)   igual   sort(maior)
  else:
    return num

nnum = int(input(""))
num = []

for i in range(nnum):
 numeros = int(input(""))
 num.append(numeros)

for x in num:
 outln(sort(x))

The objective here is to print the list num in different lines, and i could do that easily with a print instead of an outln, but in this exercise i need to do it with an outln so i created the for to print each element of the list. I cant figure out what the problem is so maybe you guys could help me out.

CodePudding user response:

You cannot use len function on the type int

>>> n = 5
>>> 
>>> len(n)
Traceback (most recent call last):
   File "<pyshell#5>", line 1, in <module>
    len(n)
TypeError: object of type 'int' has no len()
>>> 
>>> 
>>> n = '5'
>>> 
>>> len(n)
1

You must convert int to str before passing it to the len function:

 len(str(num))

CodePudding user response:

int doesn't have a __len__ method attached to it. If you want to check it's length do, len(str(num)). This is a possible duplicate of TypeError: object of type 'int' has no len() error assistance needed

  • Related