0

If I use .index in a list it will always return the first element that come up. But what if they were duplicates and I wanted their indexes as well? For example:

listm=["shell","shell","use"]
listm.index("shell")

It will return 0 but there are 2 "shell"s. How would I get the index of both?

Largecooler21
  • 147
  • 3
  • 12

2 Answers2

2

By using a list comprehension with enumerate:

>>> ind = [i for i, j in enumerate(listm) if j == 'shell']
>>> print(ind)
[0, 1]
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
0

Using : list comprehension + enumerate,

In [26]: listm = ["shell","shell","use"]

In [27]: [i for i,j in enumerate(listm) if j == "shell"]
Out[27]: [0, 1]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52