Search code examples
pythonpython-3.xfunctiondictionaryiterable-unpacking

Unpacking of list in function but not needed when its done with MAP()?


def ups(*name):
    for n in name:
        a=n.upper()

    return a
lis=["lan","ona"]
m=list(map(ups,lis))
print(m)

Here in the map I have not done unpacking of the list, but the same in case of function call for without Map(), (eg) like ups(*lis) is must, why is that?

Learning, Thanks


Solution

  • In addition to ksourav's answer,

    • In the docs you find that map(function, iterable, ...) "Return[s] an iterator that applies function to every item of iterable, yielding the results". As ksourav points out in his answer, the items you pass are strings and thus iterables themselves - so the function just returns the last letter in uppercase, like
    s = 'lan'
    for char in s:
        print(char.upper())
    # L
    # A
    # N
    
    • What * does (in this case) is turning the argument (=string) passed into a 1-element tuple - you now iterate over the tuple and not the individual elements of the string anymore. This is why here, your function returns the whole word in uppercase letters, like
    t = ('lan',)
    for element in t:
        print(element.upper())
    # LAN
    
    • By the way, a more readable way of writing your function could imho be
    m = list(map(lambda x: x.upper(), lis))
    # or even better
    m = [s.upper() for s in lis]