Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 477
Sibbs Gambling Avatar asked Oct 03 '13 07:10

Sibbs Gambling


People also ask

How do you split a list in Python evenly?

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.

How do you select odd indices in Python?

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.


1 Answers

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]
like image 95
Martijn Pieters Avatar answered Oct 19 '22 07:10

Martijn Pieters