11
votes

What is the most Pythonic way of splitting up a list A into B and C such that B is composed of the even-indexed elements of A and C is composed of the odd-indexed elements of A?

e.g. A = [1, 3, 2, 6, 5, 7]. Then B should be [1, 2, 5] and C should be [3, 6, 7].

1

1 Answers

29
votes

Use a stride slice:

B, C = A[::2], A[1::2]

Sequence slicing not only supports specifying a start and end value, but also a stride (or step); [::2] selects every second value starting from 0, [1::2] every value starting from 1.

Demo:

>>> A = [1, 3, 2, 6, 5, 7]
>>> B, C = A[::2], A[1::2]
>>> B
[1, 2, 5]
>>> C
[3, 6, 7]