Daniel Dorman
Daniel Dorman

Reputation: 75

list returns empty after appending data

sorry for this simple(hopefully) question:

my code:

end_result = []

def func():
    end_result = []
    data= [1,2,3,4,5,6,7,8,9]
    for i in data:
        if i not in end_result:
            end_result.append(i)

func()
print(end_result)

adding the line end_result = [] at the top of the function to reset the list before adding the data outputs:

[]

and removing it outputs:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

why is this? In my code I need the end_result = [] to be reset and empty before adding/re-adding information to it. Alternately is there another way to empty the list that might work instead of my following method?(if it's required to make the code work)

Thanks for the help and thanks for tolerating my bad question haha

Upvotes: 3

Views: 1416

Answers (1)

Unmitigated
Unmitigated

Reputation: 89254

You can just use the global keyword.

def func():
    global end_result
    end_result = []
    data= [1,2,3,4,5,6,7,8,9]
    for i in data:
        if i not in end_result:
            end_result.append(i)

func()
print(end_result)

However, it makes more sense to return the list instead of assigning to a global variable.

def func():
    end_result = []
    data= [1,2,3,4,5,6,7,8,9]
    for i in data:
        if i not in end_result:
            end_result.append(i)
    return end_result

res = func()
print(res)

The method would be more reusable if data were a parameter instead of a local variable as well.

def func(data):
    end_result = []
    for i in data:
        if i not in end_result:
            end_result.append(i)
    return end_result

res = func([1,2,3,4,5,6,7,8,9])
print(res)

Upvotes: 4

Related Questions