Convert a flat list to list of lists in python
NickName:oz123 Ask DateTime:2012-04-12T21:38:17

Convert a flat list to list of lists in python

One may want to do the contrary of flattening a list of lists, like here: I was wondering how you can convert a flat list into a list of lists.

In numpy you could do something like:

>>> a=numpy.arange(9)
>>> a.reshape(3,3)
>>> a
array([[0, 1, 2],
   [3, 4, 5],
   [6, 7, 8]])

I was wondering how you do the opposite, and my usual solution is something like:

>>> Mylist
['a', 'b', 'c', 'd', 'e', 'f']
>>> newList = []
for i in range(0,len(Mylist),2):
...     newList.append(Mylist[i], Mylist[i+1])
>>> newList 
[['a', 'b'], ['c', 'd'], ['e', 'f']]

is there a more "pythonic" way to do it?

Copyright Notice:Content Author:「oz123」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/10124751/convert-a-flat-list-to-list-of-lists-in-python

Answers
jamylak 2012-04-12T13:40:16

>>> l = ['a', 'b', 'c', 'd', 'e', 'f']\n>>> zip(*[iter(l)]*2)\n[('a', 'b'), ('c', 'd'), ('e', 'f')]\n\n\nAs it has been pointed out by @Lattyware, this only works if there are enough items in each argument to the zip function each time it returns a tuple. If one of the parameters has less items than the others, items are cut off eg.\n\n>>> l = ['a', 'b', 'c', 'd', 'e', 'f','g']\n>>> zip(*[iter(l)]*2)\n[('a', 'b'), ('c', 'd'), ('e', 'f')]\n\n\nIf this is the case then it is best to use the solution by @Sven Marnach\n\nHow does zip(*[iter(s)]*n) work",


Sven Marnach 2012-04-12T13:41:32

This is usually done using the grouper recipe from the itertools documentation:\n\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return itertools.izip_longest(fillvalue=fillvalue, *args)\n\n\nExample:\n\n>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']\n>>> list(grouper(2, my_list))\n[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', None)]\n",


Ryan M 2015-04-29T03:48:01

Another way to create a list of lists can be simplified as shown below:\n\n>>>MyList = ['a','b','c','d','e','f']\n# Calculate desired row/col\n>>>row = 3\n>>>col = 2\n>>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]\n>>>NewList\n[['a', 'b', 'c'], ['d', 'e', 'f']]\n\n\nThis can method can be extended to produce any row and column size. If you select row and column values such that row*col >len(MyList), the sublist (row) containing the last value in MyList will end there, and NewList will simply be filled with the appropriate number of empty lists to satisfy the row/col specifications\n\n>>>MyList = ['a','b','c','d','e','f','g','h']\n>>>row = 3\n>>>col = 3\n>>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]\n>>>NewList\n[['a', 'b', 'c'], ['d', 'e', 'f'], ['g','h']]\n\n>>>row = 4\n>>>col = 4\n>>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]\n[['a', 'b', 'c', 'd'], ['e', 'f', 'g','h'], [], []]\n",


More about “Convert a flat list to list of lists in python” related questions

Convert a flat list to list of lists in python

One may want to do the contrary of flattening a list of lists, like here: I was wondering how you can convert a flat list into a list of lists. In numpy you could do something like: >>> a=

Show Detail

making a list of lists and strings into a flat list

I have the following lista that contains lists and strings: ['IBERDROLA', 'ACCOR\xa0SA', ['ADMIRAL'], ['ADECCO', 'IAG']] I would like to make it a flat_list with this output: [&#

Show Detail

Performance: Multidimensional Lists vs Flat List

I am using very large lists of lists in python to do some maths with, but then it started lagging quite a bit (~20 seconds). I then started comparing multidimensional and flat lists. Code from t...

Show Detail

Convert flat data into a hierarchical python list

I have a data model from my database. This is a flat python list sorted by left values. > id name left right > 1 Beginning 1 6 > 2 FOO 2 5 > 3 BA...

Show Detail

flatten list of lists of lists to a list of lists

I've already searched SO for how to flatten a list of lists (i.e. here:Making a flat list out of list of lists in Python) but none of the solutions I find addresses flattening a list of lists of li...

Show Detail

Convert a flat list of points to two dimensional System.Array type Array[Array[Point]] in Python

I am working with Surfaces in Python. I am trying to make a NurbsSurface from a list of control points. However, original data that is available to me is in flat list. Since in order to create a su...

Show Detail

List of lists and integers into list

I have a python list of lists that includes integers and I need to convert it into a single list. If the list did not include any integers (only other lists) I could use the solution provided here:

Show Detail

Python convert a list of lists into a list of tuples

I'm trying to convert lists of lists into lists of tuples. My Python 2.6.8 code is: 1. dicts = List of dictionaries all with same set of keys foo and bar 2. for d in dicts: 3. for f ...

Show Detail

Best way to convert a flat list to a set of two-tuples in Erlang?

Is there a fast way to convert a flat list into a list of two-tuples such that a flat list like [1,2,3,4,5,6] becomes [{1,2},{3,4},{5,6}]? This works, but it feels just plain WRONG:

Show Detail

Reading a list of lists from a file as list of lists in python

I collected data in the form of list of lists and wrote the data into a text file. The data in the text file looks like [[123231,2345,888754],[223467,85645]] I want to read it back and store in ...

Show Detail