[Python] Confused about declaring lists outside vs. inside loops and creating them empty vs....

Discussão em 'Python' iniciado por Stack, Outubro 5, 2024.

  1. Stack

    Stack Membro Participativo

    I'm learning about creating a list of lists. For this particular section, this was the correct code:

    numerical_list = []

    for line in nested_list:
    name = line[0]
    count = float(line[1])
    new_list = [name, count]
    numerical_list.append(new_list)

    print(numerical_list[0:5])


    They give you a little bit of instruction, including creating the empty numerical_list before starting the loop, but I'm slightly confused as to why I need to declare that empty list while, in the body of the loop, I was able to create

    new_list = [name, count]


    Without declaring it outside. I think I get it, but I want to be sure.

    My understanding is that, because numerical_list is empty, it needs to be declared outside of the loop so that it exists and then, on the line

    numerical_list.append(new_list)


    I'm inserting an element into it. Meanwhile, because I'm declaring new_list with arguments, it already has elements and they don't need to be inserted separately. Is that correct?

    In other words, is this correct: new, empty lists cannot be created inside a loop but new lists with arguments can.

    Continue reading...

Compartilhe esta Página