Given a list
a = [0,1,2,3,4,5,6,7,8,9]
how can I get
b = [0,9,1,8,2,7,3,6,4,5]
That is, produce a new list in which each successive element is alternately taken from the two sides of the original list?
Given a list
a = [0,1,2,3,4,5,6,7,8,9]
how can I get
b = [0,9,1,8,2,7,3,6,4,5]
That is, produce a new list in which each successive element is alternately taken from the two sides of the original list?
You can just
pop
back and forth:Note: This destroys the original list,
a
.For fun, here is an itertools variant:
This works where
len(a)
is even. It would need a special code for odd-lengthened input.Enjoy!
One way to do this for even-sized lists (inspired by this post):