0

I want to search through a python list and print out the index of each occurrence.

a = ['t','e','s','t']
a.index('t')

The above code only gives me the first occurrence's index.

CoderDude
  • 13
  • 5
  • you would have to loop through the list yourself and record the indices – Mike Tung Mar 21 '19 at 01:52
  • Do you know about `enumerate(a)` and list comprehensions? – smci Mar 21 '19 at 01:58
  • I've heard about `enumerate()`, but I did not know how to use it in this way. – CoderDude Mar 21 '19 at 02:05
  • 1
    CoderDude: sure. Anytime you find yourself writing `for i in range(len(something))` it's always a code smell for `enumerate(something)`. And since that avoids needing a loop, it suggests a list comprehension (possibly with a condition). – smci Mar 21 '19 at 02:53
  • 1
    Do you only want to find occurrences of the item 't' (as your code implies), or all elements in the list (as your title implies)? The latter is more generalizable for the rest of us. Can you please fix either your title or your code? – smci Apr 10 '19 at 05:53
  • This question was asked when I was very inexperienced with Python, as well as StackOverflow. This is a definite duplicate of [How to find all occurrences of an element in a list](https://stackoverflow.com/q/6294179/10611444) – CoderDude Dec 25 '22 at 07:25

4 Answers4

2

You can use a list comprehension with enumerate:

a = ['t','e','s','t']
indices = [i for i, x in enumerate(a) if x == 't']

Inside of the list comprehension, i is the current index and x is the value at that index.

iz_
  • 15,923
  • 3
  • 25
  • 40
  • Surely you mean `[(i,x) for i, x in enumerate(a)]`? Otherwise you're only comparing for `x == 't'`, not for all elements. – smci Apr 10 '19 at 03:44
  • @smci Sorry, I am quite confused as to what you are saying. How does what I have not find all of the indices? What is the output supposed to be? – iz_ Apr 10 '19 at 03:46
  • What you have only finds the occurrences of the item 't'. Not of all items. the question said "look through a list and print out each occurrences' index number". – smci Apr 10 '19 at 05:40
  • 1
    @smci The way I interpret the title is to look for all occurrences of a single item. Nothing in the question suggests "all items." Of course, if you can give some elaboration as to where exactly OP specified "all items" rather than a single item, that would be appreciated. – iz_ Apr 10 '19 at 06:23
  • there's no need for labored sarcasm. The title clearly conflicts with the first line which says *"look through list and print out **each occurrences'** index number"*, like I said. Given a choice between interpreting it such as not to give a very reusable resource (e.g. just for item 't'), we should choose the more general way ("all items"). – smci Apr 10 '19 at 06:27
1

With enumerate inside list comprehension for t,

>>> list1 = ['t','e','s','t']
>>> all_index = [i for i, j in enumerate(list1) if j == 't']
>>> all_index

Output:

[0, 3]

With loop for all element,

list1 = ['t','e','s','t']
result = {}
for e in list1:
    result[e] = [i for i, j in enumerate(list1) if j == e]
print(result)

Output:

 {'s': [2], 'e': [1], 't': [0, 3]}
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • Your 1st solution is fine. Your 2nd solution should be written without the inefficient double loop, and it should not calculate `result['t']` twice. – PM 2Ring Apr 10 '19 at 08:50
0

Yes you can do it with enumerate

[x[0] for x in enumerate(a) if x[1]=='t']

Out[267]: [0, 3]
BENY
  • 317,841
  • 20
  • 164
  • 234
  • This certainly works, but using indices is more verbose & slightly slower than tuple unpacking, like Tomothy32's answer uses. – PM 2Ring Apr 10 '19 at 09:02
0
def get_indices(my_list, item):
    result = []
    for i in range(len(my_list)):
        if my_list[i] == item:
            result.append(i)
    return result

Then try it out...

>>> get_indices(a, "t")
[0, 3]
Simon Thomas
  • 187
  • 1
  • 4
  • This is what `enumerate()` is for. No need for loops. List comprehensions all the way. Cleaner, shorter, more Pythonic. – smci Mar 21 '19 at 01:57
  • But a good, working solution nonetheless. I personally prefer the looping method. – Pika Supports Ukraine Mar 21 '19 at 02:02
  • 1
    @PikachuthePurpleWizard: why? it's a clunky, obfuscated, non-Pythonic solution; less efficient and slower. It's the sort of thing a Java coder generates. It shows no understanding of Python idiom. `for i in range(len(list))` is always a code smell for `enumerate(list)` – smci Mar 21 '19 at 02:52
  • @smci well, I am a java coder. I'm used to lots of loops. But, my point is, even though it doesn't use a builtin utility method, it still works perfectly well. – Pika Supports Ukraine Mar 21 '19 at 02:53
  • 1
    Please do not shadow built-in names like `list`. It won't hurt anything in your `get_indices` function, but in general it can lead to errors with mysterious error messages if subsequent code attempts to call `list`. And we don't want new coders reading SO answers picking up such bad habits. – PM 2Ring Apr 10 '19 at 08:59