Search code examples
pythonpython-3.xlistfunctionreturn

Why does this for-loop return an empty list?


This is what i currently have:

messages = {
  "Placeholder": 0,
  "1": 48,
  "2": 4,
  "3": 31,
  "4": 2
}

def pls():


    messages_sorted = sorted(messages, key=messages.get, reverse=True)

    for i in range(10):
        output = []
        try:
            currp = str(messages_sorted[i])
            if currp == "Placeholder":
                print("PLACEHOLDER DETECTED")
                return output
            currpp = messages[currp]
            output.append(f"{currp} has {currpp} and is Place {i+1}")
            print(output)

        except IndexError:
            print("Index error")

        except:
            print("some other error")
    
    return output

output = pls()
output = str(output)
output = output.replace("['", "")
output = output.replace("']", "")
print(output)

I already used this question's Answer to make the different Outputs one List, however when i run it, it returns an empty List. When i remove the following part:

if currp == "Placeholder":
            print("PLACEHOLDER DETECTED")
            return output

I just get a bunch of Index Errors. The

print(output)

inside the for-loop gets me exactly what i need in the Console (as different strings), however i cant return it as a List or variable . How can i do that?


Solution

  • Your output=[] is inside your for loop. So at each iteration, its value is reinitialized, you should try again with output=[] before the for loop