Skip to content

Instantly share code, notes, and snippets.

@IvanFrecia
Created May 3, 2021 16:01
Show Gist options
  • Save IvanFrecia/7ab38759a61c4db8d9eb0d54736e85e8 to your computer and use it in GitHub Desktop.
Save IvanFrecia/7ab38759a61c4db8d9eb0d54736e85e8 to your computer and use it in GitHub Desktop.
Data Collection and Processing with Python - Week 2 - 23.2. Map
# 1) Using map, create a list assigned to the variable greeting_doubled that doubles each element in the
# list lst.
lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4]
greeting_doubled = map((lambda a_list: a_list * 2), lst)
print(greeting_doubled)
# Output:
# [['hi', 'bye', 'hi', 'bye'], 'hellohello', 'goodbyegoodbye', [9, 2, 9, 2], 8]
# 2. Below, we have provided a list of strings called abbrevs. Use map to produce a new list called
# abbrevs_upper that contains all the same strings in upper case.
abbrevs = ["usa", "esp", "chn", "jpn", "mex", "can", "rus", "rsa", "jam"]
abbrevs_upper = map(lambda string: string.upper(), abbrevs)
print(abbrevs_upper)
# Output:
# ['USA', 'ESP', 'CHN', 'JPN', 'MEX', 'CAN', 'RUS', 'RSA', 'JAM']
@miriamputter
Copy link

Unfortunately, this code is not working to 100% and is showing only 80% of the result.
Why?

@osazemeu
Copy link

@miriamputter you need to cast to list because it returns an iterable.

@miriamputter
Copy link

@miriamputter you need to cast to list because it returns an iterable.

How do I do that? Can you write the complete code?

@MeowmyofSix
Copy link

For the first one:

greeting_doubled=list(map((lambda value: 2*value), lst))
print(greeting_doubled)

For the second one:
abbrevs_upper=list(map(lambda x: x.upper(), abbrevs))
print(abbrevs_upper)

@miriamputter
Copy link

For the first one:

greeting_doubled=list(map((lambda value: 2*value), lst)) print(greeting_doubled)

For the second one: abbrevs_upper=list(map(lambda x: x.upper(), abbrevs)) print(abbrevs_upper)

Thank you!

@henryd0
Copy link

henryd0 commented Oct 16, 2022

lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4]
greeting_doubled = list(map((lambda value: 2*value), lst))
print(greeting_doubled)

@henryd0
Copy link

henryd0 commented Oct 16, 2022

you can use this instead

@henryd0
Copy link

henryd0 commented Oct 16, 2022

and for the second one

abbrevs_upper = list(map((lambda str: str.upper()), abbrevs))
print(abbrevs_upper)

@joegrippi
Copy link

Thanks! I forgot in the latest version of python you have to cast to list in these cases...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment