Python Forum

Full Version: Convert Generator into List
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys,

I understand that in order to convert a Generator object to a List, it is as simple as casting a list(<Object Generator>). However, this in my code does not work. I have several functions in another module called script_data, and these return an Object Generator, specifically this: <generator object titulo_obras at 0x036533E0>.
These functions should return all a list, but I don't return them with return but with yield, so I understand that I'm forming an iterator.
This is my main code to put the data of the lists in my personal database:

import script_datos
import mysql.connector
import more_itertools


try:
    conn = mysql.connector.connect(host="localhost",port=3306,db="mydb",user="root",password="")
    children_col = script_datos.html_data() #This returns a Generator Object, same as others functions
    col_html = script_datos.html_data_col()
    print("Connection established sucessfully")
    titulos = script_datos.titulo_obras(children_col)
    print(titulos)
    sinopsis = script_datos.sinopsis_obras(children_col)
    tit_org = script_datos.tit_original(children_col)
    dibujantes = script_datos.dibujo_obras(children_col)
    guion = script_datos.guion_obras(children_col)
    ed_franc = script_datos.edicion_francesa(children_col)
    ed_amer = script_datos.edicion_americana(children_col)
    ed_jap = script_datos.edicion_japonesa(children_col)
    ed_esp = script_datos.edicion_española(children_col)
    genero = script_datos.generos_obras(children_col)
    formato = script_datos.formatos_obras(children_col)
    sent_lect = script_datos.sent_lectura_obras(children_col)
    tomos_jap = script_datos.numeros_japon(children_col)
    tomos_esp = script_datos.numeros_españa(children_col)
    cursor = conn.cursor()
    for i in list(titulos):
        print(i)
    cursor.executemany("INSERT INTO `colección`(`Id.coleccion`, `titulo`, `sinopsis`, `titulo_org`, `dibujante`, `guion`, `ed.francesa`, `ed.americana`, `ed.japonesa`, `ed.española`, `genero`, `formato`, `sent.lectura`, `tomos_jap`, `tomos_esp`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",0, str(titulos[ind]), str(sinopsis[ind]), str(tit_org[ind]), str(dibujantes[ind]), str(guion[ind]), str(ed_franc[ind]), str(ed_amer[ind]), str(ed_jap[ind]), str(ed_esp[ind]), str(genero[ind]), str(formato[ind]), str(sent_lect[ind]), str(tomos_jap[ind]), str(tomos_esp[ind]))
    print("Se han añadido correctamente todas los datos")
    conn.commit()
except mysql.connector.Error as e:
    print("Failed to insert record into MySQL table {}".format(error))
finally:
    if (conn.is_connected()):
        cursor.close()
        conn.close()
        print("MySQL connection is closed")
I need to get the indexes of each of the elements in the lists, however with the Object Generator I don't know how to do that. With the lists it would be as easy as making an .index().
If I try to cast a list, for example:
titulos = list(script_datos.titulo_obras(children_col)).
If I try to print the list or try to browse through it, it doesn't return anything.
Do you know how I can get the indexes from the Generator or how to convert it to list?
I think the problem is that you are using children_col several times. Look at this example where I define a generator 'spam'
>>> def spam():
...     for x in range(5):
...         yield x**2
... 
>>> s = spam()
>>> s
<generator object spam at 0x7ff9d3628678>
>>> list(s)
[0, 1, 4, 9, 16]
>>> list(s)
[]
The first time I call list(s), it creates the list by traversing the generator s, but then the generator is 'exhausted'. The second time I call list(s), it returns the empty list.

The solution is to convert s to list immediately because a list can be traversed several times
>>> s = list(spam())
>>> list(s)
[0, 1, 4, 9, 16]
>>> list(s)
[0, 1, 4, 9, 16]