0
How do I get index of an element of multiple occurence in python?
So I want to find all words that are >=5 in a list. Here's the code: ############################### list1 = input("Enter the sentence: ") list1 = list1.split() width = [] for word in list1: if len(word)>=5: width.append(list1.index(word)) ############################### Now let's say I input: "This sentence is a sentence cuz sentence", then it saves the indexes as [1,1,1] since that's the first occurrence. But I can't figure out a way to get indexes of all occurrences of the word. Any help?
5 Answers
+ 2
# You do not evaluate the length of the word?
# You could iterate over the list using the length of list1 and append the index to width if the word at this index is >= 5.
# .index() will only ever return the index of the first occurrence
# Here is a list comprehension example:
x = "tree tree sun tree".split()
out = [idx for idx, word in enumerate(x) if len(word) == 4]
print(out)
+ 2
If the code qualifies words by length (match specific length), then what should happen when there are other words (different words) having same length e.g. 'sentence' and 'prisoner' have same length. Should index of 'prisoner' be included in result?
+ 1
Ipang Yep all words of 5 or greater length are to be included
0
Nvm guys, found it:
for i, ch in enumerate(list2):
if len(ch)>=5:
width.append(i)
print(width)
It was pretty easy, didn't need to bang my head 10 times on the table:)
0
Lisa Forgot to put len() in the question:/
Thanks for the answer, its a great help!