andytheman
andytheman

Reputation: 11

how to use the .count function with lists within a range

This will all be an example, so this is not my actual code:

list1 = ["hi","hello", "whats up", "hi","whats up"]
print(list1.count("hi"))

And I guess my question is, can I make it count within a specific range? The following code will be an example of what I thought I could do, but it was invalid syntax:

list1 = ["hi","hello", "whats up", "hi","whats up"]
print(list1.count(0:4, "hi"))

Can somebody help me out?

Upvotes: 0

Views: 87

Answers (2)

Thaddaeus Markle
Thaddaeus Markle

Reputation: 524

You got the first part right. list1.count("hi") returns 2, because there are two elements that are the string "hi" in list1.

In the second part, you are misunderstanding how the count function works. The count function only takes one argument - the element to find in the list (or tuple, string, etc). Instead what you need to do is slice the list - basically, make a copy of the list with only a given range of the elements. So instead of list1.count(0:4, "hi"), you need to do list1[0:4].count("hi") (as Jonas said). That makes a copy of the list and operates count on that copy, not operate on the original list with a parameter telling the function to only look in a specific part.

For more info on slicing see https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/ or just google "python list slicing". See also https://www.programiz.com/python-programming/methods/list/count.

Edit:

Interestingly enough, the string count function has a different signature (different parameters) than the list count fuction. The string count function has, in adition to the value to search for, two optional arguments - the start and the end of the search. So for a string s = "hi hello whats up hi whats up" you could do s.count("hi", 0, 4) or s[0:4].count("hi"). For more info on the string count fuction, see https://www.programiz.com/python-programming/methods/string/count.

Upvotes: 1

Jonas
Jonas

Reputation: 1769

You can do this:

print(list1[0:4].count("hi"))

Upvotes: 2

Related Questions