Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items from list by using python list comprehensions

Tags:

python

list

I have a list of integers which goes like this:

unculledlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

I would like cull the values from this list, so that it looks like this:

culledlist = [0, 2, 4, 10, 12, 14, 20, 22, 24]

But I would like to do this by using list comprehensions.

This is a graphical preview of how I am trying to cull the list values. It's easier to understand if I arrange the list values into rows and columns. But this is only visually. I do not need nested lists: enter image description here

I can do it by using two nested loops:

unculledlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

index = 0
culledlist = []
for i in range(6):
    for j in range(5):
        if (i % 2 == 0) and (j % 2 == 0):
            culledlist.append(unculledlist[index])
        index += 1

print "culledlist: ", culledlist  # culledlist = [0, 2, 4, 10, 12, 14, 20, 22, 24]

But I would like to do it with python list comprehensions instead.

Can anyone provide an example please?

Thank you.

EDIT:

The reason why I would like to use list comprehensions is because my actual unculledlist has a couple of million of integers. Solving this issue with list comprehensions will definitively speed things up. I do not care about readability. I just want to make a quicker solution.

I can not use numpy nor scipy modules. But I can use itertools module. Not sure if solution with itertools would be quicker than the one with list comprehensions? Or even lambda?

like image 656
marco Avatar asked Dec 26 '15 18:12

marco


3 Answers

I saw this and thought string manipulation would be the easier approach

culled_list = [item for item in unculledlist if str(item)[-1] in ['0','2','4']]

The result is still a list of integers

>>> culled_list
[0, 2, 4, 10, 12, 14, 20, 22, 24]

Thanks to eugene y for the less complicated approach

>>> culled_list = [item for item in unculledlist if item % 10 in (0,2,4)]
>>> culled_list
[0, 2, 4, 10, 12, 14, 20, 22, 24]
like image 167
PyNEwbie Avatar answered Oct 02 '22 21:10

PyNEwbie


You can do it with a list comprehension like this:

[x for i, x in enumerate(unculledlist) if (i % 6) % 2 == 0 if (i % 5) % 2 == 0]

The output is:

[0, 2, 4, 10, 12, 14, 20, 22, 24]
like image 43
enrico.bacis Avatar answered Oct 02 '22 21:10

enrico.bacis


You could read the list in 5-items chunks and extract elements with even indexes from every even chunk:

>>> [x for i, v in enumerate(range(0, len(unculledlist), 5)) if not v % 2 for x in unculledlist[v:v+5:2]]
[0, 2, 4, 10, 12, 14, 20, 22, 24]
like image 22
Eugene Yarmash Avatar answered Oct 02 '22 22:10

Eugene Yarmash