user2048206
user2048206

Reputation: 13

No Count function on Python on my Raspberry Pi

When I try to use the 'list.count' function on my raspberry Pi it comes up with

   Name Error: name 'count' is not defined

Is there any thing I can do about it? Thank you in advance for any help. I am using Python. I am just starting out with Python and in my tutorial it states

   >>>count(seq,'a')

With 'seq' being a sequence of letters that I entered earlier. I expect it is meant to count the number of 'a's in the sequence.453

Thank you all very much for your quick responses and answers, I have now fixed the problem. This was my first ever online question that I asked so thank you again. The second answer by Markus Unterwaditzer finally solved the problem with 'seq.count('a')'

Also thanks to DSM for finding the tutorial and explaining why I had my problem. Everything works now and I am back to learning my first computer language.

Upvotes: 1

Views: 238

Answers (3)

DSM
DSM

Reputation: 353419

Ah. The magic in the tutorial is in the

from string import *

line, which is bad practice. It imports everything from the string module into scope, including the function string.count:

>>> print string.count.__doc__
count(s, sub[, start[,end]]) -> int

    Return the number of occurrences of substring sub in string
    s[start:end].  Optional arguments start and end are
    interpreted as in slice notation.

count is also a method of strings, so you can write

>>> 'aaa'.count('a')
3

which is generally preferred. In modern Python, the string module doesn't even have a count function.

Upvotes: 4

Markus Unterwaditzer
Markus Unterwaditzer

Reputation: 8244

>>> seq = ['a', 'b', 'c', 'a']
>>> seq.count('a')
2
>>> type(seq) is list  # the reason it's mentioned as list.count
True
>>> list.count(seq, 'a')  # the same thing, but nobody does it like that
2

Upvotes: 1

Mike
Mike

Reputation: 49463

I expect it is meant to count the number of 'a's in the sequence

Depending on what list is, that's probably not the correct syntax. If list is a string you can do this:

>>>a = "hello"
>>>a.count('h')
1
>>>a.count('l')
2

Works the same for a "list":

>>>a = ['h','e','l','l','o']
>>>a.count('l')
2

Upvotes: 1

Related Questions