LaN tHe MaN
LaN tHe MaN

Reputation: 45

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

Upvotes: 2

Views: 198

Answers (2)

FObersteiner
FObersteiner

Reputation: 25634

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]

Upvotes: 2

ksouravdas
ksouravdas

Reputation: 124

star()args means variable number of arguments.so basically your fuction can take variable number of arguments.On the other hand map function takes a function and a list as argument and the function is called on each element of the list that was passed as argument.so If you don't use "" in the function which you have defined, then it will take one sting in the lis(as you are passing in to the map function) and iterate over it and return the only last letter of each string in uppercase.Because for loop will iterate over the element passed but return only the last element as you are returning only a.

Upvotes: 0

Related Questions