0

I have the list which looks something of this sort. I wanted to know if there is any quick way to create sub list out of this?

list = [1,2,3,4,5,6,7,8,.....]

What is the best way in python to split list into this sublist?

1. [(1, 2), (3, 4), (5, 6), ...]
2. [(1, 2, 3), (4, 5, 6), ...]
3. [(1,2,3,4),(5,6,7,8), ....]
user2510612
  • 45
  • 1
  • 1
  • 6

2 Answers2

5

You can achieve this quite easily by looping over the list with a step equivalent to the number of elements you want in each sublist (e.g. range(0, len(a), n)). You can extract the elements you need for each sublist using indexing (e.g. a[i:i+n]). For example:

def group(a, n):
    return [tuple(a[i:i+n]) for i in range(0, len(a), n)]


print group([1, 2, 3, 4, 5, 6], 2)
# [(1, 2), (3, 4), (5, 6)]

print group([1, 2, 3, 4, 5, 6], 3)
# [(1, 2, 3), (4, 5, 6)]

print group([1, 2, 3, 4, 5, 6, 7, 8], 4)
# [(1, 2, 3, 4), (5, 6, 7, 8)]
grc
  • 22,885
  • 5
  • 42
  • 63
0

Try numpy.reshape:

>>> import numpy
>>> a = range(1,7)
>>> a
[1, 2, 3, 4, 5, 6]
>>> numpy.reshape(a,(3,2))
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> numpy.reshape(a,(2,3))
array([[1, 2, 3],
       [4, 5, 6]])

reshape takes an "array like" object and a tuple containing the numbers of rows and columns of the new matrix.