python finds multiple index instances of the same element in a list

  • 2021-06-28 12:55:28
  • OfStack

Definition: X=[1,2,3,1,4]

Task: Find an index of element 1

Solution:


#  If used directly X.index(1), Only available 0 this 1 Indexes , And we need all the indexes .
l = len(X)
zip_list = zip(*(range(l),X))
id1 = [z[0] for i,z in enumerate(zip_list) if z[1]==1]

#  Or simpler 
id1 = [i for i,x in enumerate(X) if x==1]

Related articles: