JGrazza
JGrazza

Reputation: 75

Counting evens in a two-dimensional list?

Hey guys I'm trying to make a program that counts the evens in a two-dimensional list. The program I made so far is not returning what I want it to.

def Evens(x):
    count = 0
    x = len(x)
    for a in range(x):
        if a%2 == 0:
            count = count + 1
    return count

that keeps returning 2 for the list Evens([[1,3],[1,9,7,1,3],[13]]) when I want it to return 4. I tried everything but it seems to not be working correctly.

Thanks

Upvotes: 0

Views: 183

Answers (4)

Volatility
Volatility

Reputation: 32300

You need to actually iterate over the sublists.

def evens(l):
    count = 0
    for l2 in l:
        for i in l2:
            if i%2 == 0:
                count += 1
    return count

Or you can you can take a much simpler approach.

def evens(l):
    return sum(i%2==0 for l2 in l for i in l2)

The second approach uses the fact that in an integer context, True == 1 and False == 0, so you would get the expected result.

Upvotes: 3

root
root

Reputation: 80346

You need to iterate over all the sublists:

In [34]: l = [[1,4,3],[12,0,7,10,3],[13]]

In [35]: sum(n%2 == 0 for sub in l for n in sub)
Out[35]: 4

Upvotes: 2

Blender
Blender

Reputation: 298246

You need to iterate over the elements in each sublist as well:

def count_evens(l):
    total = 0

    for l2 in l:
        for item in l2:
            if item % 2 == 0:
                total += 1

    return total

What you were doing before was iterating over the number of sublists (i.e. [0, 1, 2, 3] for a list with 4 elements). Your code was working, but it wasn't working properly.

Upvotes: 0

Michael J. Barber
Michael J. Barber

Reputation: 25042

The problem you're encountering is that you are checking the indices to see if they are even, not the values. You're also not checking in the sublists.

More straightforward, IMO, is to do this:

import itertools
def evens(x):
    return sum(a % 2 == 0 for a in itertools.chain.from_iterable(x))

Upvotes: 3

Related Questions