0

I have a list L = [1,2,3,4,5,6] and I need to retrieve pairs as follows:

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

My current solution is create two utility lists:

U1 = [1,2,3,4,5]
U2 = [2,3,4,5,6]

And use zip built in function to get the desired result.

Is there any better way to achieve the same?

Dilshad Abduwali
  • 1,388
  • 7
  • 26
  • 47

2 Answers2

3

That's like your solution with the utility lists but a bit shorter:

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

for i in zip(L, L[1:]):
    print(list(i))
# [1, 2]
# [2, 3]
# [3, 4]
# [4, 5]
# [5, 6]

This works as expected because zip stops as soon as one iterable is exhausted.

You could additionally use map to convert the items immediatly:

for i in map(list, zip(L, L[1:])):
    print(i)

or if you want the whole thing converted to a list of lists:

list(map(list, zip(L, L[1:])))
# [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]

If your lists are really long creating a new list (because I sliced it with [1:]) might be expensive, then you could avoid this by using itertools.islice:

for i in zip(L, islice(L, 1, None)):
    print(list(i))
MSeifert
  • 145,886
  • 38
  • 333
  • 352
1

Use a list comprehension:

[[L[i], L[i+1]] for i in range(len(L)-1)]

Usually, a list comprehension will be much faster than a for loop in python

Greg Jennings
  • 1,611
  • 16
  • 25
  • List comprehensions are **usually** only faster in constructing lists in iteration, however are not faster in the case of iteration for other purposes: http://stackoverflow.com/questions/22108488/are-list-comprehensions-and-functional-functions-faster-than-for-loops – the_constant Jan 18 '17 at 00:51