2

I have this list

list = ['c', 'h', 'a', 'l', 'l', 'e', 'n', 'g', 'e']

however when I call list.index("e") it only returns the first index. Is there any way to return both indexes?

Sumtinlazy
  • 337
  • 5
  • 17

3 Answers3

3

You can do this:

>>> list_ = ['c', 'h', 'a', 'l', 'l', 'e', 'n', 'g', 'e']
>>> [index for index, value in enumerate(list_) if value == 'e']

Which is the equivalent of:

list_ = ['c', 'h', 'a', 'l', 'l', 'e', 'n', 'g', 'e']

result = []
for index, value in enumerate(list_):
    if value == 'e:'
        result.append(index)

The former example (list comprehensions) is more compact and faster than an explicit for loop. This is because calling .append() on a list causes the list object to grow (in chunks) to make space for new elements individually, while the list comprehension gathers all elements first before creating the list to fit the elements in one go.

As a function, more general, where the element you want the index for might change:

def get_all_indexes(list_, element):
    return [index for index, value in enumerate(list_) if value == element]

print(get_all_indexes(['c', 'h', 'a', 'l', 'l', 'e', 'n', 'g', 'e'], 'e'))
2

I'd do something like this, using list comprehension, please notice not to use list as a variable name:

>>> myList = ['c', 'h', 'a', 'l', 'l', 'e', 'n', 'g', 'e']    
>>> [i for i, v in enumerate(myList) if v == "e"]
[5, 8]
Vinícius Figueiredo
  • 6,300
  • 3
  • 25
  • 44
1

or you can use numpy

import numpy as np
list = ['c', 'h', 'a', 'l', 'l', 'e', 'n', 'g', 'e']
np.where(np.array(list)=="e")

if you want to it to get it in list,you can use

np.where(np.array(list)=="e")[0].tolist()

i would strongly advise you not call your variables keywords like like list,dict? just call it my_list or another name

Eliethesaiyan
  • 2,327
  • 1
  • 22
  • 35