-1

I need to write a function that if a number is in the list, then the function will return a list of positions of that number in the list. If the number is not in the list, it will return 0.

Here is the code that I have written.

def find_member_positions(number,list_of_numbers):
    number = int
    list_of_numbers = []
    
    for number in list_of_numbers:
        position = list_of_numbers.index(number)
    return position

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135

1 Answers1

-1

The index() method always finds the first occurrence of the specified value

Try this:

def find_member_positions(number,list_of_numbers):
    position=[]
    
    for i, num in enumerate(list_of_numbers):
        if num == number:
            position.append(i)
    return position
print(find_member_positions(number=1,list_of_numbers = [1,2,1,3,1,4,1,5,1,6]))
[0, 2, 4, 6, 8]

Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.

Here I am enumerating over the list and checking for my number and recording the index!

If you can use numpy:

import numpy as np
list_of_numbers = np.array([1,2,1,3,1,4,1,5,1,6])
number = 1
answer = np.where(list_of_numbers == number)[0]
print(answer)
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22