Published: Oct. 8, 2019 by lukemakin |  estimated reading time: 6 minutes
While working with lists, we often need to apply some some operations on them, or simply get only the items that meet the given condition. Instead of writing for loops, which in some cases are inconvenient to use - we can look at map and filter functions. If we want to keep the code as short as possible, in some cases it might be a good idea to use conditional list comprehension. In this article we will go through an example that is related to grades: 1) translating the grades (i.e. of a test in college) 2) getting the number of not passed test. Please note that we are using 6 and "A" as the highest grades  both equal to each other, while 1 and "F" are the lowest ones (but also equal).

So our main list looks like the one below:

test_results = [1, 3, 5, 4, 3, 2, 1, 1, 5, 6, 3]

Now let's translate the numbers to letters. We can use the map function that will apply some logic defiened in another function on all the items of the list.


def get_grade(x):
if x == 6:
return "A"
elif x == 5:
return "B"
elif x == 4:
return "C"
elif x == 3:
return "D"
elif x == 2:
return "E"
elif x ==1:
return "F"
else:
return "we got an error"

grades = list(map(get_grade, test_results))
print(grades)

'''
results:
['F', 'D', 'B', 'C', 'D', 'E', 'F', 'F', 'B', 'A', 'D']
'''

To get the number of not passed tests we need to use the filter function, which will return only the items that meet the given condition. So we need to define a new function or use the lambda:


def get_F_grade(x):
if(x) == 1:
return x


not_passed = len(list(filter(get_F_grade, test_results)))
print(not_passed)

'''
result:
3
'''

And below our example with the use of the lambda function:


not_passed = len(list(filter(lambda x: x == 1, test_results)))
print(not_passed)

'''
result:
3
'''

If we would like to keep the code even shorter we could use the conditional list comprehension, but we need to keep in mind that our code could become less clean and readable.

Let's translate the grades with conditional list comprehension:

r_all = ["A" if x == 6 else 'B' if x == 5 else "C" if x == 4 else "D" if x == 3 else "E" if x == 2 else "F" if x == 1 else "we got an error" for x in test_results]

print(r_all)

'''
results:
['F', 'D', 'B', 'C', 'D', 'E', 'F', 'F', 'B', 'A', 'D']
'''

And now we can look at the not passed tests number retrieved by the use of conditional list comprehension:


r_not_passed = len([1 for x in test_results if x==1])
print(r_not_passed)

'''
result:
3
'''

So this is it for this article. In my opinion map and filter are better and cleaner solutions. On the other hand with the use of conditional list comprehension we can often write less lines of code.

 
Extras
To view additional content login or create a free account
Categories:
Share your thoughts

No comments yet...

Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019 pyplane.com