Python’s Lists: Grab the odd and even elements in a list

Lists in Python

Let’s show some nice syntax with Python and list in case you need to take even or odd only elements from a list.

numbers = [1,2,3,4,5,6,7,8,9]

We can have number, strings, object etc.

Even elements or items in a list

To get the even items you just do this:

even = numbers[1::2])

This means that starting from index 1 (that is the second element, the number 2, because lists starts from index 0, not 1 as you could think): to the end to the list (the end is omitted, there is nothing after the first column :, we get each item every two position. So we grab  all the even numbers:

['2', '4', '6']

If you start from number 0, of course, you would have the odd numbers.

In the square brackets you should have [start:stop:step]. The stop is omitted, meaning you go ’til the end of the list,

Odd elements in the list

To get the odd numbers you just start from the first elment, the number 1 with and index of 0 (because lists starts with a 0 index).

even = numbers[0::2])

So, starting from the very first number(index 0, but element is 1) with a step of 2, you got:

['1', '3', '5', '7']

With Python things are extemely easy, as you can see.

Utilities

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.