2

I have a list with letters:

list1 = [abcdefghijk]

I have num = 3 and want to break list1 in parts of 3, i.e:

[[abc], [def], [ghi], [jk]]

My code is:

for i in range(0, len(list1), num):
    chunks = [list1[i:i+num]]

I get wrong output:

chunks = ['k']

But I expect:

chunks = [[abc],[def],[ghi],[jk]]

I have gone through all the available solutions here. But they did not help. How should I fix this?

Yaroslav Admin
  • 13,880
  • 6
  • 63
  • 83
Explore_SDN
  • 217
  • 1
  • 3
  • 10

5 Answers5

3

First of all you don't need to put the string in a list since it's an iterable, and if it's so you can get it out and out the string in a variable and use python grouper function from itertools-recipes to grouping your string with chunks and then use a list comprehension to join them :

from itertools import izip_longest
def grouper(iterable, n, fillvalue=''):
    args = [iter(iterable)] * n
    return izip_longest(*args, fillvalue=fillvalue)

[''.join(i) for i in grouper(list1,3)]

produces

['abc', 'def', 'ghi', 'jk']

Note: for python 3 use zip_longest instead

Pynchia
  • 10,996
  • 5
  • 34
  • 43
Mazdak
  • 105,000
  • 18
  • 159
  • 188
3
>>> list2 = 'abcdefghijk'
>>> [list2[i:i+num] for i in range(0, len(list2), num)]
['abc', 'def', 'ghi', 'jk']

How it works

i:i+num is a slice: it selects starting at index i and continuing up to but not including index i+num. For example:

>>> list2[6 : 6+3]
'ghi'

We want to perform slices every three characters. To get the i values that we need, we use the range function:

>>> range(0, len(list2), num)
[0, 3, 6, 9]

Now, we want to slice list at each of the indices supplied by range. Thus:

>>> [ list2[i:i+num] for i in range(0, len(list2), num) ]
['abc', 'def', 'ghi', 'jk']

This form is called list comprehension.

John1024
  • 109,961
  • 14
  • 137
  • 171
2

You overwrite the value stored in the variable chunks in every iteration of your loop. Therefore your solution is not working, this could be solved to adjust your code in the following way:

list1 = 'abcdefghijk'
chunks = []
for i in range(0, len(list1), num):
    chunks.append( list1[i:i+num] )

A more pythonic way of solving your problem is the following one-liner:

[list1[i:i+num] for i in range(0, len(list1), num)]

This is called list comprehension.

martijnn2008
  • 3,552
  • 5
  • 30
  • 40
0
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
num = 3
chunks = []
for i in range(0,len(list1), num):
      chunks.append([list1[i:i+num]])
print chunks
Vikas Ojha
  • 6,742
  • 6
  • 22
  • 35
0

Another solution, with no indexes and one pass only

list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
num = 3
chunks = []
chunk = ''

for pos, el in enumerate(list1, 1):
    chunk += el
    if not pos % num:
        chunks.append(chunk)
        chunk = ''
chunks.append(chunk)

print chunks

produces

['abc', 'def', 'ghi', 'jk']
Pynchia
  • 10,996
  • 5
  • 34
  • 43