0

I have an assignment here:

Given an array of ints, return the number of 9's in the array.

array_count9([1, 2, 9]) → 1
array_count9([1, 9, 9]) → 2
array_count9([1, 9, 9, 3, 9]) → 3

I have 2 ideas for this, one is:

def array_count9(nums):
    count = 0
    list1 = [x for x in nums if x==9]
    return len(list1)

and the other:

def array_count9(nums):
    count = 0
    for n in nums:
        if n==9:
            count +=1
    return count

But I wonder which way would be more Pythonic, in terms of performance, clarity,... ? Thank you very much

Mazdak
  • 100,514
  • 17
  • 155
  • 179
Dang Manh Truong
  • 685
  • 2
  • 8
  • 35

1 Answers1

6

The most Pythonic way would be to use a built-in function, count in this case. Try this:

def array_count9(nums):
  return nums.count(9)
Óscar López
  • 225,348
  • 35
  • 301
  • 374
  • 1
    @TruongTroll if this answer was helpful for you, please don't forget to [accept](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) it, just click on the check mark to its left ;) – Óscar López Nov 14 '15 at 23:06