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)
Fun with iter
:
it = iter(l)
zip(it, it)
# [(0, 1), (2, 3), (4, 5)]
You can also slice in strides of 2 and zip
:
list(zip(l[::2], l[1::2]))
# [(0, 1), (2, 3), (4, 5)]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments