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)
CodePudding user response:
The results array was not defined in the function, before appending elements to it. Also you forgot to return the results array at the end of the function
def throwing_6(x):
results = []
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)
CodePudding user response:
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)
CodePudding user response:
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]