[Solved] List of even numbers at even number indexes using list comprehension [closed]


I wasn’t able to figure out exactly what you were looking for from your post, but here’s what I think you want:

Given a list, get all the numbers at even indices. If any of these numbers are even, put them in a new list and return it:

In [10]: L = [3,1,54,5,2,3,4,5,6,5,2,5,3,2,5,2,2,5,2,5,2]

In [11]: [num for i,num in enumerate(L) if not num%2 and not i%2]
Out[11]: [54, 2, 4, 6, 2, 2, 2, 2]

If you want to add 0s in between, then you can do a little itertools magic:

In [12]: list(itertools.chain.from_iterable(zip((num for i,num in enumerate(L) if not num%2 and not i%2), itertools.cycle([0]))))[:-1]
Out[12]: [54, 0, 2, 0, 4, 0, 6, 0, 2, 0, 2, 0, 2, 0, 2]

Ok, that was a lot of brackets and parentheses, so let’s take a closer look at it:

  1. list(...)[:-1] converts ... into a list and gets all but the last element of that list. This is similar to what you were trying to do when you added 0s and removed the last one

  2. (num for i,num in enumerate(L) if not num%2 and not i%2) is the same as what it was before the edit, except that it uses parentheses (()) instead of brackets ([]). This turns it into a generator-comprehension, as opposed to a list comprehension – it only matters in that it performs a little bit of optimization – the values are not computed until they are needed (until zip asks for the next value)

  3. itertools.cycle([0]) gives an endless list of 0s

  4. zip(A, B) returns a list of tuples, in which the ith tuple has two elements – the ith element of A, and the ith element of B

  5. itertools.chain.from_iterable(zip(A, B)) returns the elements of A and B interleaved, as a generator. In essence, it’s like doing this:


def someFunc(A, B):
    for i in range(len(A)):
        yield A[i]
        yield B[i]

Thus, all of these put together give you exactly what you want

2

solved List of even numbers at even number indexes using list comprehension [closed]