Skip to content Skip to sidebar Skip to footer

List Of Even Numbers At Even Number Indexes Using List Comprehension

I am trying to generate an even numbered list at even index locations using a list comprehension. The else values will be 0. I have done the function which does the same as below d

Solution 1:

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

Solution 2:

You can try this based on your expected output.But you must know list comprehension is nothing more or less than for loop.

input = [11, 17, 12, 17, 40, 19, 12, 16] 
>>>[k forjin [[i,0] foriin input if i%2 == 0] forkin j][:-1]
[12, 0, 40, 0, 12, 0, 16]

Solution 3:

>>>list(map(lambda x: x if x % 2 == 0else0, range(10)))
[0, 0, 2, 0, 4, 0, 6, 0, 8, 0]

range(10) generates a list with integers from 0 to 9. To this list I apply a map, which transforms all odd numbers in the list into 0, and doesn't do anything with the even numbers (lambda x: x if x % 2 == 0 else 0).

Then I cast this map back into a list to get a nice print.

Solution 4:

>>>[x if x%2 == 0else0for x inrange(20)]
[0, 0, 2, 0, 4, 0, 6, 0, 8, 0, 10, 0, 12, 0, 14, 0, 16, 0, 18, 0]

Post a Comment for "List Of Even Numbers At Even Number Indexes Using List Comprehension"