Wednesday, December 20, 2023

Remove Duplicate Items from a Python List

#Remove duplicate item from Python List old_list = ['k','l','k','m','m','n','o'] new_list =[] for element in old_list: if element not in new_list: new_list.append(element) #print(new_list) #['k', 'l', 'm', 'n', 'o'] #2nd Approach: old_list = ['k','l','k','m','m','n','o'] #new_list = dict.fromkeys(old_list) #{'k': None, 'l': None, 'm': None, 'n': None, 'o': None} new_list = dict.fromkeys(old_list).keys() #dict_keys(['k', 'l', 'm', 'n', 'o']) new_list = list( dict.fromkeys(old_list).keys() ) print(new_list) #['k', 'l', 'm', 'n', 'o']


No comments:

Post a Comment