Search code examples
pythondictionarysetcoding-style

How to use map and set on Python


Is there a way to make this a bit cleaner? I have to keep transforming everything to a list after doing an operation and this line of code is just bothering me. I'm kind of new to programming and wish to have something more presentable. This solution works for me, however it is a bit ugly.

exclusion_new = ["Abs", "acd", "bde", "Abs", "Kji"]  #example list
x = list(set(list(map(lambda x: x.lower(), exclusion_new))))
print(x)
result: ["abs", "acd", "bde", "kji"]

Solution

  • You can remove one call of list():

    exclusion_new = ["Abs", "acd", "bde", "Abs", "Kji"]  #example list
    x = list(set(map(lambda x: x.lower(), exclusion_new)))
    

    Furthermore using a map-function in combination with lambda is overkill in this scenario.

    You should use a simple list comprehension instead:

    exclusion_new = ["Abs", "acd", "bde", "Abs", "Kji"]  #example list
    x = set([x.lower() for x in exclusion_new])
    

    Alternatively a set comprehension:

    exclusion_new = ["Abs", "acd", "bde", "Abs", "Kji"]  #example list
    x = [*{x.lower() for x in exclusion_new}]