Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Check the occurrences in a list against a value

Tags:

lst = [1,2,3,4,1] 

I want to know 1 occurs twice in this list, is there any efficient way to do?

like image 851
user469652 Avatar asked Dec 15 '10 03:12

user469652


People also ask

How do you count how many times a value appears in a list?

Use the COUNTIF function to count how many times a particular value appears in a range of cells. For more information, see COUNTIF function.

How do you check if an element occurs more than once in a list Python?

Method 1: Using the index() Method The index() function in Python searches for an element in a list and returns its index. If the element occurs more than once in the list, the index of its first occurence is returned and if the element is not present in the list, the function raises a ValueError.


1 Answers

lst.count(1) would return the number of times it occurs. If you're going to be counting items in a list, O(n) is what you're going to get.

The general function on the list is list.count(x), and will return the number of times x occurs in a list.

like image 145
逆さま Avatar answered Sep 20 '22 12:09

逆さま