Home > OS >  Python- list of lists with values.tolist()
Python- list of lists with values.tolist()

Time:11-28

I need to read a single column from db table as a list of values. I tried to do that with following line of code:

ids_list = (pd.read_sql_query(q, db_internal.connection)).values.tolist()

when I use the values.tolist() it does what documentation says, that is turns the df into list of lists:

[['0x0043Fcb34e7470130fDe28198571DeE092c70Bd7'],
 ['0x00f93fBf00F97170B6cf295DC58888073CB5c2b8'],
 ['0x01FE650EF2f8e2982295489AE6aDc1413bF6011F'],
 ['0x0212133321479B183637e52942564162bCc37C1D']]

Because I am reading single column, I would like to transform it into list of values, not list of lists:

 ['0x0043Fcb34e7470130fDe28198571DeE092c70Bd7',
 '0x00f93fBf00F97170B6cf295DC58888073CB5c2b8',
 '0x01FE650EF2f8e2982295489AE6aDc1413bF6011F',
 '0x0212133321479B183637e52942564162bCc37C1D']

What would be a way to do that? I keep on finding solutions that are focused on list of lists

CodePudding user response:

You can simply iterate through the list with:

[i for i in ids_list[0]]

I hope this helps.

CodePudding user response:

Just convert tolist() generated list into list with the first element only.

ids_list = list(i[0] for i in (pd.read_sql_query(q, db_internal.connection)).values.tolist())
  • Related