Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter out only items from a list which is in an even position?

Tags:

python

Instead of processing items based on its value, I need to run a function based on the item's position. This is an example of filtering based on the content of the list.

only_words = filter(str.isalpha, my_list)

I want to create a slice of the list that contains only items in the even position, that is:

new_list = []
pos = 0
for item in my_list:
   if pos % 2 == 0:
       new_list.append(item)

This is way too ugly. Better suggestions ?

like image 781
Frankie Ribery Avatar asked Jun 21 '11 08:06

Frankie Ribery


1 Answers

You can use this: my_list[::2] (for odd — my_list[1::2])

like image 152
DrTyrsa Avatar answered Oct 02 '22 19:10

DrTyrsa