How to return the count of odd and even numbers in a list?

953 Views Asked by At

Using a for loop in Python write code to iterate through every number in the list below to separate out even and odd numbers. Then return the number of odd and even numbers in the list.

my_numbers = [12, 21, 33, 14, 57, 6, 17, 10, 11, 28, 3, 32, 2, 4]

This is what I have so far:

my_numbers = [12, 21, 33, 14, 57, 6, 17, 10, 11, 28, 3, 32, 2, 4]
splitevenodd(A) 

def splitevenodd(A): 
   evenlist = [] 
   oddlist = [] 
   for i in my_numbers: 
      if (i % 2 == 0): 
         evenlist.append(i) 
      else: 
         oddlist.append(i) 
   print("Even list:", evenlist) 
   print("Odd list:", oddlist) 
    

my_evennumbers = ["Even list:"]
my_oddnumbers = ["Odd list:"]

print("The total count of numbers in my list is", len(my_numbers))

##counting the even numbers
#print("The count of even numbers in my list is", len(my_evennumbers))

##counting the odd numbers
#print("The count of odd numbers in my list is", len(my_oddnumbers))

I am not sure why this is not working. I am trying to get it to print how many numbers are in each, the even and the odd list. I think I am defining my_evennnumbers wrong but I am not sure how to define it in a way where it knows what I am asking it to count.

6

There are 6 best solutions below

3
Jesse Sealand On

I would use list comprehension for this one. This lets you assign the lists directly in a single line. Then you can just calculate the counts with only iterating over the list one.

my_numbers = [12, 21, 33, 14, 57, 6, 17, 10, 11, 28, 3, 32, 2, 4]

even_count = len([x for x in my_numbers if x%2==0])
odd_count = len(my_numbers) - even_count
0
Jabrove On

This worked for me:

def splitevenodd(A): 
   evenlist = [] 
   oddlist = [] 
   for i in my_numbers: 
      if (i % 2 == 0): 
         evenlist.append(i) 
      else: 
         oddlist.append(i) 
   print("Even list:", evenlist) 
   print("Odd list:", oddlist) 

my_numbers = [12, 21, 33, 14, 57, 6, 17, 10, 11, 28, 3, 32, 2, 4]

splitevenodd(my_numbers) 

For it to work, I had to define the function first, then define the list, then pass the list to the function. The order of definition matters.

0
LetzerWille On
numbers_even = [x for x in my_numbers if x % 2 == 0]

numbers_odd = list(set(my_numbers).difference(set(numbers_even)))

print(numbers_even)

print(numbers_odd)

[12, 14, 6, 10, 28, 32, 2, 4]
[33, 3, 11, 17, 21, 57]
0
tdelaney On

You could count the odds and then the evens are whatever is left over. A fast way is to use the sum function to add the first bit of each integer.

my_numbers = [12, 21, 33, 14, 57, 6, 17, 10, 11, 28, 3, 32, 2, 4]
odds = sum(number & 1 for number in my_numbers)
evens = len(my_numbers) - odds
print(odds, evens)

sum is implemented in C and will be a bit faster than modulos or conditionals written in python.

0
Adam Smith On

Your code doesn't work because, while your function does separate out the evens and odds, it never does anything with those results. You could simply return the lists:

def splitevenodd(my_numbers): 
    evenlist = [] 
    oddlist = [] 
    for i in my_numbers:
        if (i % 2 == 0):
            evenlist.append(i)
        else:
            oddlist.append(i)
    # let's omit the prints -- we don't care about seeing it on screen here
    # print("Even list:", evenlist) 
    # print("Odd list:", oddlist)

    return evenlist, oddlist

my_numbers = [12, 21, 33, 14, 57, 6, 17, 10, 11, 28, 3, 32, 2, 4]
evens, odds = splitevenodd(my_numbers)

print(f"""\
There are {len(evens)} even numbers: {evens}
There are {len(odds)} odd numbers: {odds}
Out of a total of {len(my_numbers)} numbers.""")

However, you might also want to consider different approaches. For instance, while it's not idiomatic in Python to approach the problem this way, what you are doing is called a "fold." Folds are implemented in Python using functools.reduce, which takes some an iterable, an initial value, and some function to apply. You could, for instance, implement sum by writing:

def add(a, b):  # this is just operator.add
    return a+b

def sum(list_of_nums):
    """Folds using the add function"""
    return functools.reduce(add, list_of_nums, 0)

# if your list of numbers is...
numbers = [1, 2, 3, 4]

# then
result = sum(numbers)

# is going to start with 0+1=1 (the zero coming from the initial value)
# 1 + 2 = 3
# 3 + 3 = 6
# 6 + 4 = 10

You could use this to create your even and odd lists!

def splitevenodd(my_numbers):
    # the function to fold with!
    def _inner(accumulator, next_):
        evens, odds = accumulator  # unpack the acc
        if next_ % 2 == 0:
            evens.append(next_)
        else:
            odds.append(next_)
        # return the next state of the accumulator
        return (evens, odds)

    initial = ([], [])  # (evens, odds)
    return functools.reduce(_inner, my_numbers, initial)
0
Reilas On

"How to return the count of odd and even numbers in a list?

Using a for loop in Python write code to iterate through every number in the list below to separate out even and odd numbers. Then return the number of odd and even numbers in the list. ..."

Utilize a "list comprehension".

Here is an example.

a = [12, 21, 33, 14, 57, 6, 17, 10, 11, 28, 3, 32, 2, 4]
e = [x for x in a if x % 2 == 0]
o = [x for x in a if x % 2 != 0]
print(f'e, length= {len(e)}, {e}')
print(f'o, length= {len(o)}, {o}')

Output

e, length= 8, [12, 14, 6, 10, 28, 32, 2, 4]
o, length= 6, [21, 33, 57, 17, 11, 3]

"... I am not sure why this is not working. ..."

I believe you may have added the incorrect code on the second line.
There is no A, and splitevenodd hasn't been defined yet.

splitevenodd(A) 

"... I am trying to get it to print how many numbers are in each, the even and the odd list. I think I am defining my_evennnumbers wrong but I am not sure how to define it in a way where it knows what I am asking it to count. ..."

The evenlist and oddlist are part of the splitevenodd method scope, so you will not be able to access either from the enclosing scope.
Place these values outside and above the splitevenodd method.

my_numbers = [12, 21, 33, 14, 57, 6, 17, 10, 11, 28, 3, 32, 2, 4]
evenlist = []
oddlist = []

def splitevenodd(A):
    for i in my_numbers:
        if (i % 2 == 0):
            evenlist.append(i)
        else:
            oddlist.append(i)
    print("Even list:", evenlist)
    print("Odd list:", oddlist)

splitevenodd(my_numbers)

print("The total count of numbers in my list is", len(my_numbers))

##counting the even numbers
print("The count of even numbers in my list is", len(evenlist))

##counting the odd numbers
print("The count of odd numbers in my list is", len(oddlist))

Output

Even list: [12, 14, 6, 10, 28, 32, 2, 4]
Odd list: [21, 33, 57, 17, 11, 3]
The total count of numbers in my list is 14
The count of even numbers in my list is 8
The count of odd numbers in my list is 6