Anthony Martin
Anthony Martin

Reputation: 21

Even counting integers Python

Hey guys I have been having a little trouble in trying to count all of the even integers within my list and print the number of even integers. I am new to programming so may not be up to date with the knowledge and terminology of some of you guys on here. If you could help me out that would be great! Here is what i have started already.

list = [2,4,5,6,8]
count_even=0
while count_even<len(list):
    if list[count_even]%2==0:
        count_even=count_even + 1
   else:
        list[count_even]%2!=0
        count_even=count_even
   print count_even 

Upvotes: 1

Views: 486

Answers (6)

bud-e
bud-e

Reputation: 1551

list = [2,4,5,6,8]
count = 0    
for x in list:
    if x % 2 == 0:
        print "Even Number:", x
        count=count + 1
print "Count:", count

Upvotes: 3

Hackaholic
Hackaholic

Reputation: 19733

you can use map also

>>> lst = [2,4,5,6,8]
>>> map(lambda x:x%2==0,lst).count(True)
4

python 3x:

list(map(lambda x:x%2==0,lst)).count(True)

Upvotes: 1

vks
vks

Reputation: 67968

 filter(lambda x: x%2==0 ,[0,1,2,3,4,5])

You can also try the one liner.

list = [2,4,5,6,8]
count_even=0
i=0
while i<len(list):
    if list[i]%2==0:
        count_even=count_even + 1
    i=i+1


print count_even 

You are probably running an infinite loop whernever you encouter an odd number as count_even is not increasing.You need to use 2 variables.

Upvotes: 2

afinit
afinit

Reputation: 1055

list = [2,4,5,6,8]
count_even=0
for i in xrange(len(list)):
    if list[i]%2==0:
        count_even += 1
print count_even

A couple of things:

  • you are using count_even as both a counter and as an index value
  • not necessary to do anything at all if the number is not even if all you are doing is counting even numbers

Upvotes: 2

Andy
Andy

Reputation: 50540

num_list = [2,4,5,6,8]
count_even=0

for n in num_list:
    if n%2==0:
        count_even=count_even + 1
print count_even 

Explanation of changes:

  • Change list variable name. Don't use the name of a Python object.
  • Change from while to for; Don't need to do list indexing this way
  • Remove the else block; It's not doing anything right now anyway. There is no point in count_even=count_even

Your issue was with indexing. Everything was based on the count_even variable. Your while loop was continuing while it was less than the length of the list and in your else block you weren't incrementing it. Thus, you have an infinite loop if there is an odd number in the list

Upvotes: 2

101
101

Reputation: 8989

I'd make a new temporary list of even integers, then measure the length that:

lst = [2,4,5,6,8]
print len([i for i in lst if i %2 == 0])

That uses list comprehension. If you want to avoid that, just use a loop, like:

lst = [2,4,5,6,8]
count_even=0
for num in lst:
    if num %2 == 0:
        count_even += 1
print count_even

Upvotes: 4

Related Questions