Page 1 of 1

List methods

Posted: 21 Oct 2018, 18:28
by Maj123
Hello again,
I was reviewing different list methods but I am confused about the difference between list.index(x) and list.count(x). When I tried using them with different lists they give me the same output, so I don't really know what the difference between them is and the definition on our cheat sheet is also a little confusing. Here is the code I tried using these methods with:
tea = ["mint", "green", "jasmine"]
print(tea.index("green"))
print(tea.count("green"))

Both print statements print "1".

Re: List methods

Posted: 21 Oct 2018, 18:35
by Mr. MacKenty
What a great question.

Can you please wrap your code in the bbcode code blocks? It makes it easier to read :-)

COUNT tells you how many of something are in the list. Please run this code:

Code: Select all

tea = ["mint", "green", "jasmine","green","green"]
print(tea.count("green"))
INDEX tells you where the FIRST OCCURRENCE OF THE ITEM IS IN A LIST. The reason your example was weird is because "green" happens to be at position 1. Please run the 2 code examples below:

Code: Select all

tea = ["mint", "green", "jasmine","green","green"]
print(tea.index("green"))
now this code:

Code: Select all

tea = ["mint", "gunpowder", "jasmine","black","green"]
print(tea.index("green"))
In the block above, we see a 4, because that is the position (index) of the FIRST occurrence of the string green within the list "tea".

Does this make sense to you? Please reply and let me know if this answers your question.

Re: List methods

Posted: 22 Oct 2018, 20:33
by Maj123
Yes! Thank you, that answers my question my completely!