9

How can I convert a list into a list of tuples? The tuples are composed of elements at even and odd indices of the list.For example, I have a list [0, 1, 2, 3, 4, 5] and needs to be converted to [(0, 1), (2, 3), (4, 5)].

One method I can think of is as follows.

l = range(5)

out = []
it = iter(l)
for x in it:
    out.append((x, next(it)))

print(out)
Edmund
  • 675
  • 6
  • 16

3 Answers3

22

Fun with iter:

it = iter(l)
[*zip(it, it)]  # list(zip(it, it))
# [(0, 1), (2, 3), (4, 5)]

You can also slice in strides of 2 and zip:

[*zip(l[::2], l[1::2]))]
# [(0, 1), (2, 3), (4, 5)]
cs95
  • 330,695
  • 80
  • 606
  • 657
3

You can also do this with list comprehension without zip

l=[0, 1, 2, 3, 4, 5]
print([(l[i],l[i+1]) for i in range(0,len(l),2)])
#[(0, 1), (2, 3), (4, 5)]
Bitto Bennichan
  • 7,277
  • 1
  • 13
  • 38
-1

You can implement the use of Python's list comprehension.

l = range(5)
out = [tuple(l[i: i + 2]) for i in range(0, len(l), 2)]
# [(0, 1), (2, 3), (4,)]
Xteven
  • 431
  • 7
  • 9