[Python] Why does appending a list comprehension make generator objects, but appending that...

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to pull strings from an existing list, split the string by the delimiter '&', and add the two or more resulting items to a new list.

    I want to shorten my code into one line by reducing a "for" loop iteration into appending a list comprehension. But this appends generator objects, and not the split string items in the existing list.

    I run this section of code, and it appends the individual strings as list items in the new list:

    for i in sale.split('&'): thread_sold_split.append(i)

    But when I put the above "for" condition into the "append", like this:

    thread_sold_split.append(i for i in sale.split('&'))

    it starts appending generator objects. I also tried turning the appended "i" into a list object:

    thread_sold_split.append( for i in sale.split('&'))

    but this did the same thing as the previous command. Is this a limitation inherent to Python, or am I doing something wrong?

    Continue reading...

Compartilhe esta Página