6

What is the fastest and shortest method to turn this:

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

for example into this:

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

by giving the input 2 as the fixed length.

Of course there are some easy ways to make this but none of them occur to me as fast or pretty.

StrangeGirlMurph
  • 331
  • 1
  • 2
  • 14

2 Answers2

14

Why don't you try out a list comprehension?

Example:

[ids[i:i+2] for i in range(0,len(ids),2)]

Output:

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

Spiros Gkogkas
  • 432
  • 5
  • 11
0

bad but effective:

ids = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_ids = []


function = lambda x, y: [x, y]

for i in range(0, len(ids), 2):
    try:
        new_ids.append(function(ids[i], ids[i + 1]))
    except IndexError:
        new_ids.append(ids[i])
ids = new_ids
print(ids)