javasaucebiner javasaucebiner - 7 months ago 12
Python Question

Creating 2 arrays from one array in python

I am new to python coming from a Java background and am trying to create two arrays from a single array where the odd indexs are put in one array and the even index are put into another.

array one will contain indexs(0,2,4,6,8 etc.)
array two will contain indexs(1,3,5,7,9 etc.)

my current implementation is:

for i in range (0, len(originalArray) - 1):
if i % 2 == 0:
Array1.append(originalArray[i])

if i % 2 == 1:
Array2.append(originalArray[i])

if len(originalArray) % 2 == 0:
Array1.append(originalArray[-1])


Could anyone recommend a better way of doing this?
Thanks.

Answer

Assuming your list is named a

part1 = a[::2]
part2 = a[1::2]

Result:

>>> a = [1, 2, 3, 4, 5, 6]
>>> a[::2]
[1, 3, 5]
>>> a[1::2]
[2, 4, 6]

The slice syntax in python is list[start:end:step]. Using list[::2], we get each second element from the list (the even ones). To get the odd elements, we add one to the list start index, and so use list[1::2].

A more detailed explanation can be found here: python list slices