Last Updated: November 19, 2020
·
2.373K
· juliengarcia

List Comprehension in Python

I would share another small tip on Python.
I'm doing the Code Academy Python Lesson (pretty cool to start with Python),
and in a specific lesson, we need to loop on a list to apply a function on each element and sum all the result.

I passed it by using the List Comprehensions.

So here is an example

score_A_B_1 = [[90.0, 97.0, 75.0, 92.0],[90.0, 97.0, 75.0, 92.0]]
score_A_B_2 = [[100.0, 92.0, 98.0, 100.0],[100.0, 92.0, 98.0, 100.0]]
score_A_B_3 = [[0.0, 87.0, 75.0, 22.0],[0.0, 87.0, 75.0, 22.0]]

scores = [score_A_B_1,score_A_B_2,score_A_B_3]

# Return the average of the number in the list
def average(lst_of_numbers):
    return float(sum(lst_of_numbers))/len(lst_of_numbers)

# Return a weighted average of all list passed as parameter
# The weight is calculate as 100% divided by the lenght of the list
# eg. if the lenght of score_A_B = 2 ==> 100 / 2 ==> 50
# but we need a percentage so
# 50 / 100 ==> 0.5
# the weight of each element will 0.5
def get_weighted_average(score_A_Bs):
    weighted_average = 0
    for score_A_B in score_A_Bs:
        weighted_average += average(score_A_B) * (100 / len(score_A_Bs)/100)

    return weighted_average

# Return the average of the all list
def get_score_average(scores):
    return average([get_weighted_average(score) for score in scores])


scores_average = get_score_average(scores)
print(scores_average)

You can see the result here

average([get_weighted_average(score) for score in scores])

The part [get_weighted_average(score) for score in scores] is the list comprehension:

I could wrote it like that:

score_average = []
for score in scores:
    score_average.append(get_weighted_average(score))

So, with list comprehension, we loop in a list, apply a function on each element and return all the results in a list

Related protips:

Flatten a list of lists in one line in Python