Sequence and item

Define a function called count that has two arguments called sequence and item .
answer given was :slight_smile:
def count(sequence, item):
count = 0
for i in sequence:
if i == item:
count += 1
return count

print count([1, 2, 1, 1], 1)

but my answer was

def count(sequence, item):
for x in sequence:
if x == item:

return sum

print count([1, 2, 1,1,1, 1], 1)

why did they use count instead of other variable? woulnt the count mean the function?

1 Like

That does raise an eyebrow… However, the function is an object in global scope, whereas the the variable refers to a local object, not in the same scope.

The only time this would be an issue is if the function was recursive.

Personally, I would be more concerned about this function shadowing the in-built count() function of Python. One rather doubts we would write it this way in a production environment.

def item_count(sequence, item):
    count = 0
    for x in sequence:
         count += 1 if x == item else 0
    return count

Now there is no risk of shadowing the built in function.

If that one line gives you pause to think, it is known as a Python ternary. The else clause is needed, so instead of adding 1, we add zero.


To add some supporting information on conditional expressions in Python, here’s the PEP which introduced them.


1 Like

Gotta love this (from the PEP):

Previous community efforts to add a conditional expression were stymied by a lack of consensus on the best syntax. That issue was resolved by simply deferring to a BDFL best judgment call.

BDFL == Benevolent Dictator for Life, i.e., Guido Van Rossum


An honourary title now, as I believe he’s stepped down from overseeing the day-to-day of Python development.

1 Like

Yes, amidst quite a bit of controversy, last year.

1 Like