Matty Ise
Matty Ise

Reputation: 13

Python: Counting Groups of Items in a List

I am working on learning Python via Codecademy and I am struggling to figure out why I am getting a return of 1 when I run this query. Note: I know I could do a sequence.count(item) but I am trying to do this without the count function. Any help would be appreciated.

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

print count([1], 7)

Upvotes: 0

Views: 412

Answers (2)

Totem
Totem

Reputation: 7369

Corrected function:

def count(sequence, item):
    rep = 0
    for i in sequence:
        if i == item:
            rep += 1
    return rep

Regarding these lines:

for item in sequence:
    if item in sequence:

When you input [1] into the function, it goes:

  • for item in sequence(first and only item is 1)

  • if item is in sequence( if 1 is in the sequence... which it is)

  • then rep += 1, hence 1 is returned

for item in sequence means for each item in the sequence, do something. In your case you are merely confirming that the item is indeed in the sequence. You are in fact never even using or considering the 7 you input.

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304225

I think you confused yourself by using "item" to refer to two different things. I changed the loop variable to i.

def count(sequence, item):
    rep = 0
    for i in sequence:
        if i == item:
            rep += 1
    return rep

print count([1], 7)

Also, you probably don't want to keep setting rep to 0

Upvotes: 1

Related Questions