2

My problem was to transform the list [1,2,3,4,5] to [[1, 2], [2, 3], [3, 4], [4, 5]].

I resolved it with:

a = [1,2,3,4,5]

result = [[e, a[idx + 1]] for idx, e in enumerate(a) if idx + 1 != len(a)]

What the best way to do it?

jpp
  • 159,742
  • 34
  • 281
  • 339
massilva
  • 23
  • 3

2 Answers2

2

You can use zip:

L = [1,2,3,4,5]

res = list(zip(L, L[1:]))

This gives a list of tuples. If a list of lists is a strict requirement, you can use map:

res = list(map(list, zip(L, L[1:])))

print(res)

[[1, 2], [2, 3], [3, 4], [4, 5]]

For a generalised solution to your problem, see Rolling or sliding window iterator.

jpp
  • 159,742
  • 34
  • 281
  • 339
1

Don't know about the "best" way, but here is another way.

d = [1,2,3,4,5]

results = [[d[i], d[i+1]] for i in range(len(d) - 1)]
print(results)
# OUTPUT
# [[1, 2], [2, 3], [3, 4], [4, 5]]
benvc
  • 14,448
  • 4
  • 33
  • 54