Convert list into list of tuples of every two elements

Edmund :

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

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.

edited at
0

Comments

0 comments
Login to comment

Related