0

I have the following series and I am supposed to pinpoint with a loop the indices that contain exactly the value 6:

    x=[1, 3, 2, 1, 1, 6, 4, 2]  
results=[]

Upon making my code, however, I am getting the output none. What could be going wrong?

def throwing_6(x):
    for index,throw in enumerate(x):
        if throw==6:
            results.append(index)
    results

indexes = throwing_6([1, 2, 6, 3, 6, 1, 2, 6])
print(indexes)
    
buran
  • 13,682
  • 10
  • 36
  • 61
Kash
  • 99
  • 4
  • 5
    You need to `return results`. Right now your function does not return anything, thus it implicitly returns `None`. Also, you want to initialize `results` before trying to append – buran Oct 11 '22 at 17:04
  • 2
    Does this answer your question? [How do I get a result (output) from a function? How can I use the result later?](https://stackoverflow.com/questions/3052793/how-do-i-get-a-result-output-from-a-function-how-can-i-use-the-result-later) – buran Oct 11 '22 at 17:06

3 Answers3

1

You forgot to return the results array at the end of the function.

def throwing_6(x):
    for index,throw in enumerate(x):
        if throw==6:
            results.append(index)
    return results;

indexes = throwing_6([1, 2, 6, 3, 6, 1, 2, 6])
print(indexes)
0

Upon reading user feedback I found the solution see the code between two stars.

def throwing_6(x):
    for index,throw in enumerate(x):
        if throw==6:
            results.append(index)
    **return results**
    
indexes = throwing_6([1, 2, 6, 3, 6, 1, 2, 6])
print(indexes)
Ankit Seth
  • 729
  • 1
  • 9
  • 23
Kash
  • 99
  • 4
0

You could also use a simple list comprehension with condition as follows:

def throwing_6(x):
    return [i for i, v in enumerate(x) if v == 6]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22