10

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
  • 697
  • 6
  • 17

3 Answers3

23

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
  • 379,657
  • 97
  • 704
  • 746
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
  • 7,937
  • 1
  • 16
  • 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
  • 4
  • 9