Why doesn’t this python code work?

Asked

Viewed 263 times

1

list = [ 1, 2, 3, [7, 8, 10, [1, 2, 3, 5]], 1, [2, 3, 9]]

for a in list:
    print(type(a))
    if type(a) == list:
        print('E lista')

I don’t understand why it doesn’t work, can someone explain to me?

  • Your code is working, I just don’t know what you want to print...

  • and to go through all the lists you must make one go inside the other, I think I understood what I wanted, but in the case what you did does not print the key of the array and returns the type of the value that is inside it, in case you are reading the value of the traversed array.

  • Thank you Eduardo, you answered my question in your first comment. Sorry for the lack of clarity in my question.

  • Pedro, I reversed your issue because you don’t have to put "Solved" in the title. Instead, you can see if any of the answers below solved the problem and accept one of them (see in the FAQ how and why to do it). In this case there is only one, but if you had others, you could choose the one that best solved and accept it. If you find that none of the answers solved, you can also choose to write your own response and then mark as resolved

1 answer

6

Your code is working, just needed a few adjustments, let’s do a step-by-step analysis of it:

lista = [ 1, 2, 3, [7, 8, 10, [1, 2, 3, 5]], 1, [2, 3, 9]] # aqui tu cria tua lista de elementos

for a in lista: # define a variável "a" para cada elemento da lista
    if type(a) is list:  # verifica se algum elemento é uma lista
        print('E lista') # caso seja uma lista printa esta mensagem
    else:
        print(type(a))   # caso não seja, printa o tipo
  1. It is not a good practice to name a variable with the same name as a type.
  2. Notice inside the if the is.
  3. I changed the order of print for it to "choose" what to print, whether it’s the data type or the message (when it’s a list).

See working on IDE ONE


EDIT.:

If you want to print what is inside the internal lists, in your if will have to do another for.

lista = [ 1, 2, 3, [7, 8, 10, [1, 2, 3, 5]], 1, [2, 3, 9]]

for a in lista:
    if type(a) is list:
        for n in a:
            print(n) # printa o valor numérico (e a lista [1, 2, 3, 5])
    else:
        print(type(a))
  • 2

    A correction: if type(a) is list, for type(list) will return <class 'type'>.

  • Truth @Andersoncarloswoss, I went crazy on this kkkkkkkk, I’ll fix it, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.