Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to find the indexes of all the occurrences of element in a list with Python

6 Answers

0 votes
import numpy as np

lst = [43, 21, 67, 21, 30, 18, 21, 19, 21, 21]

lst = np.array(lst)

result = np.where(lst == 21)

print(result)
print(result[0])

     
 
'''
run:
 
(array([1, 3, 6, 8, 9]),)
[1 3 6 8 9]
 
'''

 



answered Apr 17, 2021 by avibootz
0 votes
lst = [43, 21, 67, 21, 30, 18, 21, 19, 21, 21]
 
pos = []
n = 21

for i in range(len(lst)):
    if lst[i] == n:
        pos.append(i)
        
print(pos)
 
 
      
  
'''
run:
  
[1, 3, 6, 8, 9]
  
'''

 



answered Apr 18, 2021 by avibootz
0 votes
lst = [43, 21, 67, 21, 30, 18, 21, 19, 21, 21]
 
n = 21

pos = [i for i in range(len(lst)) if lst[i] == n]

print(pos)
 
      
      
  
'''
run:
  
[1, 3, 6, 8, 9]
  
'''

 



answered Apr 18, 2021 by avibootz
0 votes
lst = [43, 21, 67, 21, 30, 18, 21, 19, 21, 21]
 
n = 21

pos = [i for i, x in enumerate(lst) if x == n]

print(pos)
 
      
      
  
'''
run:
  
[1, 3, 6, 8, 9]
  
'''

 



answered Apr 18, 2021 by avibootz
0 votes
import numpy as np
 
lst = [43, 21, 67, 21, 30, 18, 21, 19, 21, 21]
 
n = 21
 
result = np.where(np.array(lst) == n)[0]
 
print(result)

    
      
  
'''
run:
  
[1 3 6 8 9]
  
'''

 



answered Apr 18, 2021 by avibootz
0 votes
from more_itertools import locate
 
lst = [43, 21, 67, 21, 30, 18, 21, 19, 21, 21]
 
n = 21
 
result = list(locate(lst, lambda x: x == n))
 
print(result)

    
      
  
'''
run:
  
[1 3 6 8 9]
  
'''

 



answered Apr 18, 2021 by avibootz
...