Search code examples
pythonlistloopsparentheses

Remove parentheses from nested list created from loop Python


Please, do you know how to remove a parentheses'(', ')' from this code?

values_list = [] 
x = 0
for n in different_values:
   for each  in different_values:
      different_id = list((different_values))
      arg_1 = different_id[x]
      cursor.execute(sqlstmt2,arg_1=arg_1)
      rows = ((cursor.fetchmany(each)))
      index += 1
      x += 1
      print(rows)
      values_list.append(rows)
      break

print((values_list))

OUTPUT IS:

[[(105, 'David', '05.11.88', 'M', 'xxx', 'United States of America', 'republican', 'k')], [(106, 'Valli', '16.06.89', 'M', 'xxx', 'United States of America', 'republican', 'k')]]

I want to create nested list like a parameter for insert function to Google Sheet, but outside the loop.

wks.insert_rows(row=1, number=1, values=values_list)

Solution

  • Well, [[(a, b, c)], [(d, e, f)]] is a list of two entries which are each a list of one entry which is a tuple of three entries, namely a, b, and c — or d, e, and f. So If you want to "get rid" of a pair of parentheses, you mean that you want to get what's inside them. This is done by indexing the one and only element for lists and tuples:

    print(values_list)
    [[(105, 'David', '05.11.88', 'M', 'xxx', 'United States of America', 'republican', 'k')],
     [(106, 'Valli', '16.06.89', 'M', 'xxx', 'United States of America', 'republican', 'k')]]
    print([ value[0] for value in values_list ])
    [(105, 'David', '05.11.88', 'M', 'xxx', 'United States of America', 'republican', 'k'),
     (106, 'Valli', '16.06.89', 'M', 'xxx', 'United States of America', 'republican', 'k')]
    

    The result then is a list of tuples (instead of a list of lists of tuples), hence one pair of parentheses has been removed.

    If you want to keep the brackets and remove the (round) parentheses instead, you can just convert the tuples to lists:

    print([ list(value[0]) for value in values_list ])
    [[105, 'David', '05.11.88', 'M', 'xxx', 'United States of America', 'republican', 'k'],
     [106, 'Valli', '16.06.89', 'M', 'xxx', 'United States of America', 'republican', 'k']]
    

    But I guess it would be better not to create the original structure in the first place:

    rows = list(cursor.fetchmany(each)[0])
    

    This of course assumes that your fetchmany() call will always only return exactly one entry (represented by a tuple). With this code you will get the one single entry of of the results list and convert it (the tuple) to a list.

    I cannot say if these premises are true in your case. You should consider that before applying my code proposal.