-1
## Example - Find the indices in a list where the item is a multiple of 7
def multiple_7(l):
  indices_7 = []
  for i in range(len(l)):
    if(i%7 == 0):
      indices_7 += [i]
  return indices_7 ## list of all indices where the item is a multiple of 7

l = [2, 3, 7, 4, 14, 9] ## multiple_7 should return [2, 4]

print(multiple_7(l))

I get output [0] which is obviously not right...

1 Answers1

1

You need to check the i-th element inside l not the index number i itself:

def multiple_7(l):
    indices_7 = []
    for i in range(len(l)):
        if l[i] % 7 == 0:            # <---fixed here
            indices_7.append(i) 
    return indices_7 ## list of all indices where the item is a multiple of 7

l = [2, 3, 7, 4, 14, 9]  

print(multiple_7(l))

Output:

[2,4]

You can also shorten your code to:

def multiple_7(l):
    return [i for i,v in enumerate(l) if v%7==0] 

Any time you need the index (and value) of something in a list, use enumerate

Read more about list comprehensions with condition here: if/else in a list comprehension?

Matthias
  • 12,873
  • 6
  • 42
  • 48
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69