Skip to content

Instantly share code, notes, and snippets.

@cibofdevs
Created July 20, 2019 15:35
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save cibofdevs/aa3d5dc04a4d3109812d57a9939ddcb0 to your computer and use it in GitHub Desktop.
Save cibofdevs/aa3d5dc04a4d3109812d57a9939ddcb0 to your computer and use it in GitHub Desktop.
# 1. Write code to assign to the variable map_testing all the elements in lst_check
# while adding the string "Fruit: " to the beginning of each element using mapping.
lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya']
map_testing = map(lambda str: "Fruit: " + str, lst_check)
# 2. Below, we have provided a list of strings called countries.
# Use filter to produce a list called b_countries that only contains the strings from countries that begin with B.
countries = ['Canada', 'Mexico', 'Brazil', 'Chile', 'Denmark', 'Botswana', 'Spain', 'Britain', 'Portugal', 'Russia', 'Thailand', 'Bangladesh', 'Nigeria', 'Argentina', 'Belarus', 'Laos', 'Australia', 'Panama', 'Egypt', 'Morocco', 'Switzerland', 'Belgium']
b_countries = filter(lambda x: 'B' in x, countries)
# 3. Below, we have provided a list of tuples that contain the names of Game of Thrones characters.
#Using list comprehension, create a list of strings called first_names
# that contains only the first names of everyone in the original list.
people = [('Snow', 'Jon'), ('Lannister', 'Cersei'), ('Stark', 'Arya'), ('Stark', 'Robb'), ('Lannister', 'Jamie'), ('Targaryen', 'Daenerys'), ('Stark', 'Sansa'), ('Tyrell', 'Margaery'), ('Stark', 'Eddard'), ('Lannister', 'Tyrion'), ('Baratheon', 'Joffrey'), ('Bolton', 'Ramsey'), ('Baelish', 'Peter')]
first_names = [nama[1] for nama in people]
# 4. Use list comprehension to create a list called lst2 that doubles each element in the list, lst.
lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4]
lst2 = [i+i for i in lst]
# 5. Below, we have provided a list of tuples that contain students names and their final grades in PYTHON 101.
# Using list comprehension, create a new list passed that contains the names of students who passed the class
# (had a final grade of 70 or greater).
students = [('Tommy', 95), ('Linda', 63), ('Carl', 70), ('Bob', 100), ('Raymond', 50), ('Sue', 75)]
passed = [name[0] for name in students if name[1]>=70]
# 6. Write code using zip and filter so that these lists (l1 and l2) are combined into
# one big list and assigned to the variable opposites if they are both longer than 3 characters each.
l1 = ['left', 'up', 'front']
l2 = ['right', 'down', 'back']
l3 = zip(l1, l2)
opposites = list(filter(lambda s: len(s[0])>3 and len(s[1])>3, l3))
# 7. Below, we have provided a species list and a population list.
# Use zip to combine these lists into one list of tuples called pop_info.
# From this list, create a new list called endangered that contains the names of species whose populations are below 2500.
species = ['golden retriever', 'white tailed deer', 'black rhino', 'brown squirrel', 'field mouse', 'orangutan', 'sumatran elephant', 'rainbow trout', 'black bear', 'blue whale', 'water moccasin', 'giant panda', 'green turtle', 'blue jay', 'japanese beetle']
population = [10000, 90000, 1000, 2000000, 500000, 500, 1200, 8000, 12000, 2300, 7500, 100, 1800, 9500, 125000]
pop_info = list(zip(species, population))
endangered = [x1 for (x1, x2) in pop_info if x2<2500]
print(endangered)
@LuckyP86H
Copy link

Hello. Thanks for your sharing. A small minor critique for question 4(on line 25). I think i+1 should change to i*2

@Farman262
Copy link

You are absolutely right Mr. LuckyP86H

@MurariKarthikeya
Copy link

Really really thanks!

@Hrudayangam
Copy link

Hello. Thanks for your sharing. A small minor critique for question 4(on line 25). I think i+1 should change to i*2

it will give the same out for this case, but *2 would be the desired output :)

@mutairibassam
Copy link

countries = ['Canada', 'Mexico', 'Brazil', 'Chile', 'Denmark', 'Botswana', 'Spain', 'Britain', 'Portugal', 'Russia', 'Thailand', 'Bangladesh', 'Nigeria', 'Argentina', 'Belarus', 'Laos', 'Australia', 'Panama', 'Egypt', 'Morocco', 'Switzerland', 'Belgium']

b_countries = filter(lambda x: 'B' in x, countries)

If you added this country "GABON" in the list. Your code will break.

As you are checking if the capital letter 'B' is exist in the value without specifying the first index. Besides if the country name starts with small letter 'b', it will not be included in the output as you are just checking the capital letter case.


Please check my code:
b_countries = filter(lambda c: c[:1].lower() == 'b', countries)

@mutairibassam
Copy link

@cibofdevs I would recommend using two different vars when you deal with tuples instead of indexing.

instead of doing indexing
passed = [name[0] for name in students if name[1]>=70]

do this - n points to the first index, v points to the second
passed = [n for n, v in students if v >= 70]

I am not sure if this is the most efficient, but I believe it's more clearer.

@sophie48
Copy link

sophie48 commented Aug 15, 2021

l1 = ['left', 'up', 'front'] l2 = ['right', 'down', 'back'] l3 = zip(l1, l2) opposites = list(filter(lambda s: len(s[0])>3 and len(s[1])>3, l3))

can anyone write this in manual acccumulation so that i can understand

@mutairibassam
Copy link

mutairibassam commented Aug 15, 2021

@sophie48 First you need to understand the behavior of zip() function. It helps us to combine two or more iterables. (iterables means set, tuple, list, or dictionary).

For example:

letters = ("A", "B", "C")
numbers = ("1", "2", "3", "4")

x = zip(letters, numbers)

# if we print `x` the output will be a zip object, something similar to the below
<zip object at 0x2b2ba22e22c0>

# if we want to print the values we need to parse `x` to be a list.
print(list(x))

# so the output should be to the below
[('A', '1'), ('B', '2'), ('C', '3')]

if you notice "4" was dropped since the length of all the arrays should be equal. In other words, it will always be equal to the shortest size.

Extra

Below are examples on how to loop over a zip function.

for i,v in zip(l1,l2):
    # i        >        will access the items in l1
    # v        >        will access the items in l2
    print(i,v)

# expected output
# left right
# up down
# front back

# ---------------------------------------------
for i in zip(l1,l2):
    # i         >         will loop over the tuples
    print(i)

# expected output
# ('left', 'right')
# ('up', 'down')
# ('front', 'back')

     # and to access the items you need to have inner loop
    for j in i:
        print(j)

#---------------------------------------------

Now to answer your question.

As you see we are using function inside function inside function.
1- The first function is list() function which returns a list.
2- The second function is filter() which requires two arguments, function and iterators.
3- The third function is called anonymous function which does not have definition and lambda is just a python reserved word which tells the compiler this is anonymous function.

In code

l1 = ['left', 'up', 'front']
l2 = ['right', 'down', 'back']
l3 = zip(l1, l2)

# l3 = zip object
# so we need to cast l3 to be a list instead of a zip object, so this is why we've used a `list()` function.

# Let's understand the the anonymous function.

# lambda = the name of the function.
# s = the argument and the return

# so will be similar to the below code
def my_function(s):

# After that, we just use a simple arithmetic operations
len(s[0])>3 and len(s[1])>3  

# then we return the value
return s

if we just take the anonymous function and compare it to the old school way will be like the below

for i in zip(l1,l2):
	arr = []
	if len(i[0]) > 3 and len(v[1]) > 3:
		arr += [i]

# will return an empty arr as the second condition will be `false` since the length of the first index of the second tuple is `2` which is "up"

All combine in the old school way

l1 = ['left', 'up', 'front']
l2 = ['right', 'down', 'back']

for i in zip(l1,l2):
	arr = []
	if len(i[0]) > 3 and len(v[1]) > 3:
		arr += [i]

arr

@henryd0
Copy link

henryd0 commented Oct 16, 2022

map_testing = list(map(lambda str: "Fruit: " + str, lst_check))

for the first one

b_countries = list(filter(lambda str: str.startswith('B'), countries))

Second one

@Zushi-py
Copy link

Zushi-py commented Jan 31, 2023

  1. Write code to assign to the variable map_testing all the elements in lst_check while adding the string “Fruit: ” to the beginning of each element using mapping.

lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya']
map_testing = list(map(lambda str: "Fruit: " + str, lst_check))
print(map_testing)

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