Home > Software engineering >  How can I append elements to different arrays via a for-loop?
How can I append elements to different arrays via a for-loop?

Time:09-17

I have this piece of code:

Lista_enteros = []
Lista_texto = []

def recibir(*args):
    argumentos = args
    return argumentos

filtrar_args = recibir("Hola mundo", 6)

for i in filtrar_args:
    if type(i) == "<class 'int'>":
        Lista_enteros.append(i)
    else:
        Lista_texto.append(i)

print (Lista_enteros)
print(Lista_texto)

I expected to have an output like this:

[6]
['Hola mundo']

But when I execute the code, I'm getting this printed:

[]
['Hola mundo', 6]

How can I solve it?

CodePudding user response:

Use this code :if isinstance(i, int) instead of :if type(i) == "<class 'int'>":

Try this:

Lista_enteros = []
Lista_texto = []

def recibir(*args):
    argumentos = args
    return argumentos

filtrar_args = recibir("Hola mundo", 6)

for i in filtrar_args:
    if isinstance(i, int):
        Lista_enteros.append(i)
    else:
        Lista_texto.append(i)

print (Lista_enteros)
print(Lista_texto)

Output:

[6]
['Hola mundo']

CodePudding user response:

You should change this line -

if type(i) == "<class 'int'>"

to

if type(i) == int:

CodePudding user response:

<class int> is the output of the toString method of the type int. What you want is actually:

if type(i) is int:
  ...
  • Related