Dilshad Abduwali
Dilshad Abduwali

Reputation: 1458

How to read two repeated subsequent values from a list in Python?

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?

Upvotes: 0

Views: 54

Answers (2)

Greg Jennings
Greg Jennings

Reputation: 1641

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

Upvotes: 1

MSeifert
MSeifert

Reputation: 152667

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))

Upvotes: 3

Related Questions