-2

Given a list of elements, with certain similar elements in it, how do I write a code in Python to find the position of all the similar elements in it? This must be done using a for loop and if conditions within the for loop.

list1 = [5, 90, 10, 5, 100, 5]

So in this case, since 5 is the element that has repeats or ties, the output will be 0,3,5.

spidermarn
  • 959
  • 1
  • 10
  • 18
  • Have you tried anything? Any possible approaches in mind? – meowgoesthedog Mar 13 '19 at 16:16
  • Possible duplicate of [Finding the index of an item given a list containing it in Python](https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python) – SuperKogito Mar 13 '19 at 16:18
  • 1
    *"This must be done using a for loop and if conditions within the for loop."* This is what we would like to tell you as well. Try and later come back with a specific question if you're stuck. – Austin Mar 13 '19 at 16:19

4 Answers4

2

You can try to use set to find the unique set of elements in the list and then check for indexes of the repeated elements.

Try the code below:

from collections import defaultdict

list1 = [5, 90, 10, 5, 100, 5]

set1 = set(list1)
res_dict = defaultdict(list)

for x in set1:
    for i, y in enumerate(list1):
        if x == y:
            res_dict[x].append(i)

print res_dict

Output:

{90: [1], 100: [4], 10: [2], 5: [0, 3, 5]}
Jay
  • 24,173
  • 25
  • 93
  • 141
1

With enumerate inside list comprehension for 5,

>>> list1 = [5, 90, 10, 5, 100, 5]
>>> all_index = [i for i, j in enumerate(list1) if j == 5]
>>> all_index

Output:

[0, 3, 5]

With loop for all element,

list1 = [5, 90, 10, 5, 100, 5]
result = {}
for e in list1:
    result[e] = [i for i, j in enumerate(list1) if j == e]
print(result)

Output:

 {90: [1], 10: [2], 100: [4], 5: [0, 3, 5]}
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

Using np.where will get you what you want:

import numpy as np

list1 = [5, 90, 10, 5, 100, 5]

data = np.array(list1)
unique = sorted(list(set(data)))

match = {}
for i in range(len(unique)):
    match[unique[i]] = np.where(data == unique[i])[0]

print(match)
>>> {5: array([0, 3, 5]), 10: array([2]), 90: array([1]), 100: array([4])}
Nathaniel
  • 3,230
  • 11
  • 18
0

Using only a for loop and if conditions:

input_list = [5, 90, 100, 5, 100, 5]

elements = {}
result = []

for i, e in enumerate(input_list):
    if e in elements:
        if not elements[e][1]:
            result.append(elements[e][0])
            elements[e][1] = True
        result.append(i)
    else:
        elements[e] = [i, False]

print(sorted(result))