Last Updated: February 25, 2016
·
22.44K
· juliengarcia

Get Odd and Even indexed values from List in Python

Since I start to code in Python, I like the way the list are managed.
When you code in Java (version 6) for example and you want to get on the odd/even indexed values (as making x_y points from csv format), you need to go trough all the values and do the check:

int[] point_csv_array = {5, 12, 3, 21, 8, 7, 19, 102 };
//you want array_X = {5, 3, 8 ,19}
//you want array_Y = {12,21,7,102}

List<Integer> array_X = new ArrayList<Integer>();
List<Integer> array_Y = new ArrayList<Integer>();
for (int i : point_csv_array) {
    if ((i & 1) == 1) {
        array_X.add(i);
    } else {
        array_Y.add(i);
    }
}
System.out.println("array_X:" + array_X);
System.out.println("array_Y:" + array_Y);

In Python, to get the same result, you can use the slicing function:

point_csv_array = [5, 12, 3, 21, 8, 7, 19, 102]
array_X = l[::2]
array_Y = l[1:][::2]

print("array_X: " + str(array_X))
print("array_Y: " + str(array_Y))

For explanation:
l[::2]: the slicing function here (since Python 2.3) takes 1 element on 2. If you do l[::3] you will take 1 element on 3, so it will be the odd indexed numbers.
l[1:][::2]: the first [1:] slicing function here returns a list from the 2nd number til the end of the list. We take after the 1 element on 2 so it will be the even indexed numbers.