How to find all occurrences of an element in a list
You can use a list comprehension with enumerate
:
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
The iterator enumerate(my_list)
yields pairs (index, item)
for each item in the list. Using i, x
as loop variable target unpacks these pairs into the index i
and the list item x
. We filter down to all x
that match our criterion, and select the indices i
of these elements.
How do I count the occurrences of a list item?
If you only want a single item's count, use the count
method:
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
Important: this is very slow if you are counting multiple different items
Each count
call goes over the entire list of n
elements. Calling count
in a loop n
times means n * n
total checks, which can be catastrophic for performance.
If you want to count multiple items, use Counter
, which only does n
total checks.
How to find all occurrences of multiple elements in a list?
you do that: you have to use the condition 'or'
incd = ['a', 'b', 'b', 'c']
w1 = 'a'
w2 = 'b'
indeces = [i for i, x in enumerate(incd) if x == w1 or x== w2]
if you have lot of data to test: use a list
w = ['a', 'b' ,'d',...]
indeces = [i for i, x in enumerate(incd) if x in w]
How to find all occurrences of an element in a list?
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
is equivalent to:
# Create an empty list
indices = []
# Step through your target list, pulling out the tuples you mention above
for index, value in enumerate(my_list):
# If the current value matches something, append the index to the list
if value == 'whatever':
indices.append(index)
The resulting list contains the index positions of each match. Taking that same for
construct, you can actually go deeper and iterate through lists-of-lists, sending you into an Inception-esque spiral of madness:
In [1]: my_list = [['one', 'two'], ['three', 'four', 'two']]
In [2]: l = [item for inner_list in my_list for item in inner_list if item == 'two']
In [3]: l
Out[3]: ['two', 'two']
Which is equivalent to:
l = []
for inner_list in my_list:
for item in inner_list:
if item == 'two':
l.append(item)
The list comprehension you include at the beginning is the most Pythonic way I can think of to accomplish what you want.
How to find all occurrences(index) of an sublist in a list
When you append the list comprehension statement that matches indices for each item in sub_list
, you append them as lists of indices. append
will add the sublist to the indices
list as an element. That's why you're getting results as a list of lists.
If you take the loop out of the list comprehension you can see this more clearly
my_list = ["foo", "bar", "baz","foo", "bar", "baz"]
sub_list = ["bar", "baz"]
indices = []
for k in sub_list:
for i, x in enumerate(my_list):
if x == k:
indices.append(i)
print(indices)
# [1, 4, 2, 5]
However, there's an alternative method you can use to the loop, extend
, which adds the elements of the iterable sublist to the indices
list.
my_list = ["foo", "bar", "baz","foo", "bar", "baz"]
sub_list = ["bar", "baz"]
indices = []
for k in sub_list:
indices.extend([i for i, x in enumerate(my_list) if x == k])
print(indices)
# [1, 4, 2, 5]
Using extend
is also faster for larger lists (multiply my_list
by 100 and using %%timeit
gives 65.8 us for the first method and 54.7 us using extend
).
Find the list indices of all occurrences of a substring within the list
Try this:
indices = [idx for idx, s in enumerate(alphabet) if name in s]
where alphabet
is your list of strings, and name
is the desired substring.
Get all indexes for a python list
>>> l = [1,2,3,1,1]
>>> [index for index, value in enumerate(l) if value == 1]
[0, 3, 4]
Get index of ALL occurrences in a list
There's currently no single function in the standard library for this, but it's easy to write your own, e.g.:
fun <E> Iterable<E>.indexesOf(e: E)
= mapIndexedNotNull{ index, elem -> index.takeIf{ elem == e } }
This will work on any list, collection, or other iterable, of any type, and returns a List<Int>
. If there are no matching items (e.g. if the collection is empty), it returns an empty list.
Here mapIndexedNotNull()
transforms the elements, returning only the non-null ones. And takeIf()
is used to get the index only of matching elements, returning null for the rest (which will then be discarded).
This should be relatively efficient; it does a single scan through the list, and creates only a single new list with the results. (If temporary objects were a major concern, you'd probably not store the matching indices in a list at all, but simply loop through them with some forEachMatchingIndex()
function instead.)
(Thanks to Michael for the initial idea.)
Find index of an element occurs multiple time in a list
Just try enumerate
:
print([i for i, v in enumerate(sample) if v == 0])
Output:
[1, 3]
To fix up your code, try:
sample = [1, 0, 1, 0, 1]
ind = []
for i in range(0, 5):
if 0 in sample:
ind.append(sample.index(0))
sample[sample.index(0)] = 1
print(ind)
The reason your code didn't work is because after a while the 0s disappear from the list, so sample.index(0)
would give an error. You need to add a condition if 0
is still in the list sample
.
Related Topics
After Anaconda Installation, Conda Command Fails With "Importerror: No Module Named Conda.Cli"
Force Another Program'S Standard Output to Be Unbuffered Using Python
Python Spawn Off a Child Subprocess, Detach, and Exit
Integer Division by Negative Number
Why Do Some Regex Engines Match .* Twice in a Single Input String
Django Server Killed Frequently
How to Install Pyodbc on Linux
Process List on Linux Via Python
Python-Dev Installation Error: Importerror: No Module Named Apt_Pkg
Cannot Kill Python Script With Ctrl-C
Calling a Python Script from Command Line Without Typing "Python" First
How to Do Sed Like Text Replace With Python
Tkinter.Photoimage Doesn't Not Support Png Image
Cross-Platform Space Remaining on Volume Using Python
Does Python Have an Ordered Set