1

I turned a word into a list and am trying to find where the duplicate elements are.

Ex:

word = ['S', 'e', 'e', 'n']

I can currently only see word[1] with .index() but i want to find both letters.

Emi
  • 11
  • 1
  • 2
    Does this answer your question? [Index of duplicates items in a python list](https://stackoverflow.com/questions/5419204/index-of-duplicates-items-in-a-python-list) – tsamridh86 Jun 28 '21 at 03:02

2 Answers2

1

You can do something like that:

word = ['S', 'e', 'e', 'n']
duplicates = {letter: [i for i, v in enumerate(word) if v == letter] for letter in set(word)}

print(duplicates)
# Outputs {'S': [0], 'e': [1, 2], 'n': [3]}

If you want to filter only the duplicated letters:

print([letter for letter, indices in duplicates.items() if len(indices) > 1])
# Outputs ['e']
enzo
  • 9,861
  • 3
  • 15
  • 38
0

You can do some thing like this

word = ['S', 'e', 'e', 'n']
def find_index(l,letter):
    return [i for i,j in enumerate(l) if j==letter]
print(find_index(word,'e'))

#=== Output
#== [1, 2]