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]
.
The easiest way to split list into equal sized chunks is to use a slice operator successively and shifting initial and final position by a fixed number.
One way is using the range() function, such that it starts at the first odd index, 1 , and has a step value of 2 , so that it returns the odd indices 1, 3, 5, ... . Another way to obtain the odd indices of a list is using list comprehension, in which you can use a condition that will only include the odd indices.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With