1

I have this list

list=[0,1,2,3,4,2,6]

I want to make another list of tuples like this:

list=[(0,1),(1,2),(2,3),(3,4),(4,2),(2,6)]

Is there a built-in function that i can use?

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76

3 Answers3

2

You can use zip and list comprehension. listt[1:] starts from the second element. This is done because in your first pair, you have the 1st and the 2nd element. zip creates pairs and then you iterate over them and use () to store them as tuples.

A piece of advice: Do not use builtin names as variables. list in your case.

listt=[0,1,2,3,4,2,6]

result = [(i) for i in zip(listt, listt[1:])]
# [(0, 1), (1, 2), (2, 3), (3, 4), (4, 2), (2, 6)]

Benchmarking performance

Based on @prashant rana's comment, I compared the performance of zip with his approach taking a list 1 million times longer than the original list. Below are the results: zip turns out to be faster

import timeit
listt=[0,1,2,3,4,2,6]*1000000

%timeit [(listt[i],listt[i+1]) for i in range(len(listt)-1)]
%timeit [(i) for i in zip(listt, listt[1:])]

1.76 s ± 178 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
937 ms ± 46.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Sheldore
  • 37,862
  • 7
  • 57
  • 71
0
[(i, list[idx + 1]) for idx, i in enumerate(list) if idx < len(list) - 1]

[(0, 1), (1, 2), (2, 3), (3, 4), (4, 2), (2, 6)]

ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
0

There's no builtin function, but python makes it very easy to make your own. Here you go:

list = [0, 1, 2, 3, 4, 2, 6]
x = [(list[i], list[i+1]) for i in range(len(list)-1)]
Eb946207
  • 748
  • 8
  • 26
JimmyCarlos
  • 1,934
  • 1
  • 10
  • 24