Convert list into list of tuples of every two elements [duplicate]

  • A+
Category:Languages

This question already has an answer here:

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)] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: