How do I get index of an element of multiple occurence in python? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
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?

31st Dec 2021, 2:18 PM
Advik
Advik - avatar
5 Antworten
+ 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)
31st Dec 2021, 2:33 PM
Lisa
Lisa - avatar
+ 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?
31st Dec 2021, 2:35 PM
Ipang
+ 1
Ipang Yep all words of 5 or greater length are to be included
31st Dec 2021, 3:15 PM
Advik
Advik - avatar
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:)
31st Dec 2021, 2:32 PM
Advik
Advik - avatar
0
Lisa Forgot to put len() in the question:/ Thanks for the answer, its a great help!
31st Dec 2021, 3:14 PM
Advik
Advik - avatar