11

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

Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174
  • Does this answer your question? [Split a list into half by even and odd indexes?](https://stackoverflow.com/questions/11702414/split-a-list-into-half-by-even-and-odd-indexes) – Tomerikoo Nov 29 '20 at 08:52

1 Answers1

30

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]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343