TAGS :Viewed: 7 - Published at: a few seconds ago

[ How to break a list comprised of several lists into just one list? ]

I am coding in Python.

I am able to write code that returns a list of dates, which I want. Now, for every date, I would like to find the cell value for that date. In order to do that I wrote a for loop:

element = []
for item in result:
    cell_list = worksheet2.findall(item)

When I print element, the code returns the following response:

[[<Cell R6C3 '2/18/2015'>, <Cell R11C3 '2/18/2015'>], [<Cell R16C3 
'2/19/2015'>, <Cell R21C3 '2/19/2015'>, <Cell R26C3 '2/19/2015'>, <Cell R31C3 
'2/19/2015'>, <Cell R36C3 '2/19/2015'>, <Cell R41C3 '2/19/2015'>], [<Cell 
R46C3 '3/10/2015'>, <Cell R51C3 '3/10/2015'>, <Cell R56C3 '3/10/2015'>], 
[<Cell R61C3 '3/17/2015'>, <Cell R66C3 '3/17/2015'>, <Cell R71C3 '3/17/2015'>, 
<Cell R76C3 '3/17/2015'>, <Cell R81C3 '3/17/2015'>, <Cell R86C3 '3/17/2015'>, 
<Cell R91C3 '3/17/2015'>, <Cell R96C3 '3/17/2015'>], [<Cell R101C3 
'3/18/2015'>, <Cell R106C3 '3/18/2015'>, <Cell R111C3 '3/18/2015'>, <Cell 
R116C3 '3/18/2015'>, <Cell R121C3 '3/18/2015'>, <Cell R126C3 '3/18/2015'>, 
<Cell R131C3 '3/18/2015'>]]

How do I get the code to not put several lists into one list? I just want one big list with all of those cells instead of several list in one list.

Answer 1

Fast reply


Answer 2

list.extend() works, but another possibility is the += operator:

element += cell_list

Answer 3

You could use chain function to chain your lists. It returns iterator, so to convert it to list just pass it as constructor argument.

from itertools import chain

lists = [[1, 2], [3, 4, 5], [6]]
elements = list(chain(*lists))


Above code prints [1, 2, 3, 4, 5, 6].