I'm working on a project for my Intro to Programming class, and I need to count how many 9's are in a given list. I would like to save the number of how many there are to a variable, however when I try to save a variable with list.count(9)" I get an error. Is there a way to save it, or am I thinking wrong?
Asked
Active
Viewed 48 times
3 Answers
2
# create a list with random values
>>> import random
>>> my_list = list(random.randint(1,9) for x in range(10))
>>> my_list
[4, 2, 2, 2, 8, 8, 8, 8, 3, 7]
>>> from collections import Counter
>>> c = Counter(my_list)
>>> c
Counter({2: 3, 3: 1, 4: 1, 7: 1, 8: 4})
>>> c[8]
4
# drop all 8's from my_list
>>> my_list = [x for x in my_list if x != 8]
>>> my_list
[4, 2, 2, 2, 3, 7]

wildwilhelm
- 4,809
- 1
- 19
- 24
-
I did not know about Counter, thanks for showing this. Did the OP change the question? This is the second answer I have seen telling how to remove all instances of a value from the list. – tnknepp Dec 21 '16 at 14:51
-
@tnknepp Good point. Dropping the 9s from the list is in the question title, but not in the question text. P.S.: Yay plug for [`Counter`](https://pymotw.com/2/collections/counter.html), it's useful all over the place. – wildwilhelm Dec 21 '16 at 14:56
-
Ahh, right on. I thought I remembered seeing the need to drop values somewhere, but never checked the title. Sorry...now really glad I did not downvote. Upvoting now! – tnknepp Dec 21 '16 at 15:15
1
yourList.count(9) will give you the number of 9's. for removal, check this
-
1The OP already has list.count(9), but claims to have some error when saving to a variable. No downvote here, but this answer does not address the OP's question (not that you could due to the lack of detail in the original question) – tnknepp Dec 21 '16 at 14:49
0
You can do the following,
my_list = [1,5,6,9,4,9,9,2,3,9]
count_9 = sum(1 for i in my_list if i==9)
# to remove the 9s
filtered_list = [i for i in my_list if i!=9]

nael
- 1,441
- 19
- 36