my_list = [1,2,3,4,3,5]
cheak = []
def duplicate(any_list):
for things in any_list:
if things not in cheak:
cheak.append(things)
else:
pass
return cheak
if __name__ == "__main__":
duplicate(my_list)
I want the user to tell which list to remove duplicate, how can I do with this.
if __name__ == "__main__":
my_list = [1,2,3,4,3,5]
duplicate(my_list)
You have to assign my_list before passing it to duplicate. Outside the loop.
IIUC you need:
def duplicate(any_list):
cheak = []
for things in any_list:
if things not in cheak:
cheak.append(things)
else:
pass
return cheak
if __name__ == "__main__":
my_list = [1,2,3,4,3,5]
duplicate(my_list)
The following code is what you need:
def duplicate(any_list):
'''remove duplicates from list'''
cheak = []
for things in any_list:
if things not in cheak:
cheak.append(things)
return cheak
def mainFun():
my_list = [1,2,3,4,3,5]
print(duplicate(my_list))
if __name__ == "__main__":
mainFun()
Output:
[1, 2, 3, 4, 5]
Note also that the else
condition is not required.
A faster implementation and more Pythonic for what you want to do:
def duplicate(any_alist):
'''remove duplicates from list'''
return list(set(any_alist))
I have written two types of solution.
The duplicate
function uses a local variable ( func_loc_cheak
)(in function scope) and return the content of this local list.
The duplicate_glob
function uses a global variable ( cheak_global
) and it doesn't return anything because you can use this global variable without variable assignment.
I have added several print to see the behaviors and differences between the functions.
Code:
cheak_global = []
def duplicate_glob(any_list):
for things in any_list:
if things not in cheak_global:
cheak_global.append(things)
def duplicate(any_list):
func_loc_cheak = []
for things in any_list:
if things not in func_loc_cheak:
func_loc_cheak.append(things)
return func_loc_cheak
if __name__ == "__main__":
# Test lists.
my_list = [1, 2, 3, 4, 3, 5]
my_other_list = [8, 9, 0]
result = duplicate(my_list)
print("After first function call: {}".format(result))
result = duplicate(my_other_list)
print("After second function call: {}".format(result))
print("Content of 'cheak_global' before function call: {}".format(cheak_global))
duplicate_glob(my_list)
print("Content of 'cheak_global' after first function call: {}".format(cheak_global))
duplicate_glob(my_other_list)
print("Content of 'cheak_global' after second function call: {}".format(cheak_global))
Output:
>>> python3 test.py
After first function call: [1, 2, 3, 4, 5]
After second function call: [8, 9, 0]
Content of 'cheak_global' before function call: []
Content of 'cheak_global' after first function call: [1, 2, 3, 4, 5]
Content of 'cheak_global' after second function call: [1, 2, 3, 4, 5, 8, 9, 0]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.