2

I frequently run into a problem where I'm trying to make a list of lists of a certain length from a string.

This is an example where I have a string, but would like to make a list of lists of length 3:

x = '123456789'

target_length = 3

new = [i for i in x]
final = [new[i:i+target_length] for i in range(0, len(x), target_length)]

print(final)

Output:

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

So, this works, but feels so clunky.

Is there a better way to combine these arguments into one line or do you think that would make the code unreadable?

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
user6142489
  • 512
  • 2
  • 10
  • 28

2 Answers2

2

If you want to do it in one line you can just create the lists inside your comprehension:

x = '123456789'
target_length = 3

[list(x[i:i+target_length]) for i in range(0, len(x), target_length)]
>> [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
0

This does it in one line:

f2 = [[x[(j * target_length) + i] for i in range(target_length)] for j in range(target_length)]
triphook
  • 2,915
  • 3
  • 25
  • 34
  • This assumes that the length of the list is `target_length**2`, which it is in this example, but only coincidentally. – tobias_k Oct 13 '17 at 14:25
  • 1
    True. AK47's answer is the better one – triphook Oct 13 '17 at 14:50
  • You could fix or at least improve it by using `range(len(x) // target_length)` in the outer loop, then it works at least for lengths of `x` that are a multiple of the target length. – tobias_k Oct 13 '17 at 15:00