Sibbs Gambling
Sibbs Gambling

Reputation: 20355

Python - Split a List into 2 by even or odd index?

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

Upvotes: 11

Views: 11884

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121962

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]

Upvotes: 30

Related Questions