Python List remove duplicate elements














































Python List remove duplicate elements



To remove duplicate elements from the list, you need to use set() method which allows only unique keys.

Program:

This program is tested on python 3.7.

# To remove duplicates from a list, you needs
# to use set() method. set() is a special method
# in python which allows only uniques keys

# This function will work with all the type of lists
# like as list of integer, list of string, list of
# interger and string both, list of float etc.

def remove_duplicates_from_list(_list):
    return list(set(_list))

def main():
    # Remove duplicates from the list and store it in new list
    list_1 = [1, 2, 3, 4, 5, 5, 2, 1]
    list_2 = remove_duplicates_from_list(list_1)
    print (list_1)
    print (list_2)

    # Remove duplicates and store in the same list
    list_3 = [11, 22, 33, 44, 55, 66, 55, 33, 11]
    print (list_3)
    list_3 = remove_duplicates_from_list(list_3)

    # Remove duplicates from list of various types
    list_4 = [10, 20, "cppsecrets", 20, 30, ".com", 30, 40, "cppsecrets", ".com", "cppsecrets.com"]
    list_5 = remove_duplicates_from_list(list_4)
    print (list_4)
    print (list_5)

if __name__ == '__main__':
    main()

Output:

[1, 2, 3, 4, 5, 5, 2, 1]
[1, 2, 3, 4, 5]
[11, 22, 33, 44, 55, 66, 55, 33, 11]
[10, 20, 'cppsecrets', 20, 30, '.com', 30, 40, 'cppsecrets', '.com', 'cppsecrets.com']
['cppsecrets.com', 40, 10, 'cppsecrets', 20, '.com', 30]

Comments