Let's say I have a list: x = [1, 2, 4, 4, 6, 7]
What can I do to get an output that tells me that 4 appears in x[2]
and x[3]
?
Asked
Active
Viewed 29 times
-2

Daddy Donald
- 1
- 2
-
3Possible 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) – ZaxR Apr 05 '18 at 04:20
-
1This https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list would answer the second part of question – Chris Apr 05 '18 at 04:21
-
Question title and actual question don't synchronise much! – Sohaib Farooqi Apr 05 '18 at 05:14
3 Answers
0
I'm not aware of any built-in functions that can accomplish this, but certainly it can be done with a list comprehension:
indices = [i for i, num in enumerate(x) if num == 4]

SamBG
- 270
- 4
- 16
0
import numpy as np
x = np.array([1, 2, 4, 4, 6, 7])
print(x == 4)
You can use a numpy array to check the list. If the value is 4, it will show the indices that are 'True', meaning the value of that index is 4. This can work for large lists, and it will return the True/False values. Here is the output:
[False False True True False False]
As you can see, index 2 and 3 return True.

Simeon Ikudabo
- 2,152
- 1
- 10
- 27
0
You can create a dict and capture the index no :
x = [1, 2, 4, 4, 6, 7]
def place_(value_,list_):
d={}
for i,j in enumerate(list_):
if j==value_:
if j not in d:
d[j]=[i]
else:
d[j].append(i)
return d
print(place_(4,x))
output:
{4: [2, 3]}

Aaditya Ura
- 12,007
- 7
- 50
- 88