List methods

This forum is a place to ask questions about the python programming language.
Post Reply
User avatar
Maj123
Helper!
Posts: 9
Joined: 17 Sep 2018, 10:14

List methods

Post by Maj123 » 21 Oct 2018, 18:28

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".
1 x

User avatar
Mr. MacKenty
Site Admin
Posts: 88
Joined: 28 Apr 2018, 17:06
Answers: 3

Re: List methods

Post by Mr. MacKenty » 21 Oct 2018, 18:35

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.
0 x

User avatar
Maj123
Helper!
Posts: 9
Joined: 17 Sep 2018, 10:14

Re: List methods

Post by Maj123 » 22 Oct 2018, 20:33

Yes! Thank you, that answers my question my completely!
0 x

Post Reply