I want to make [1,2,3,4,5,6,7,8] into [[1,2],[3,4],[5,6],[7,8]], but can't seem to figure out how.
            Asked
            
        
        
            Active
            
        
            Viewed 60 times
        
    -3
            
            
         
    
    
        Georgy
        
- 12,464
- 7
- 65
- 73
 
    
    
        Bright Red
        
- 1
- 2
- 
                    Hey! This is a question for which there are many possible answers... Can you show what you tried so far? – rmeertens Mar 13 '17 at 08:34
- 
                    http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks – ewcz Mar 13 '17 at 08:35
- 
                    Naive and simple? `arr2 = [[arr[2*idx], arr[2*idx+1]] for idx in range(len(arr)/2)]` – BrechtDeMan Mar 13 '17 at 08:39
- 
                    `print(list(map(list, zip(*[iter(range(1,9))]*2))))` – OneCricketeer Mar 13 '17 at 08:39
- 
                    FWIW, I like `zip(*[iter(yourList)] * chunksize)` and the `itertools.zip_longest` variation, although some people complain that they're a bit cryptic. – PM 2Ring Mar 13 '17 at 08:39
- 
                    @PM2Ring Nailed it :) – OneCricketeer Mar 13 '17 at 08:40
- 
                    @BrechtDeMan You should use floor division `//` for that instead of `/`. It won't make a difference in Python 2 (although it's semantically nicer to use the correct operator), but it will in Python 3, where `/` returns a `float`. – PM 2Ring Mar 13 '17 at 08:49
2 Answers
0
            
            
        This will work:
>>> def to_matrix(l, n):
        return [l[i:i+n] for i in xrange(0, len(l), n)]
>>> l = [0,1,2,3]
>>> to_matrix(l,2)
>>> [[0, 1], [2, 3]]
Hope it helps
 
    
    
        Jeril
        
- 7,858
- 3
- 52
- 69
0
            
            
        A functional aproach:
l = [1,2,3,4,5,6,7,8]
map(list, zip(l[::2], l[1::2]))
[[1, 2], [3, 4], [5, 6], [7, 8]]
Also with iter:
it = iter(l)
zip(it, it)
[(1, 2), (3, 4), (5, 6), (7, 8)]
 
    
    
        Netwave
        
- 40,134
- 6
- 50
- 93
- 
                    Note that in Python 3 both `map` and `zip` return iterators, not lists. – PM 2Ring Mar 13 '17 at 08:47