Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Carlos Caro
Carlos Caro
9,528 Points

Could someone explain this code step by step? I am getting confused how she gets there:

def calculate_sum_succinct(data_sample): prices = [float(row[2]) for row in data_sample[1:]] # don't understand this line return sum(prices)

Steven Parker
Steven Parker
229,005 Points

It's always helpful if you include a link to the video or challenge you are referring to.

1 Answer

MARCELLO BARROS FILHO
MARCELLO BARROS FILHO
3,842 Points

let's try to understand piece by piece (I modify the code to make it easier to understand the logic):

data_sample = [(1, 2, 3, 5, 12), (4.4, 5.5, 6, 7),
               (0, 2.4, 6.5, 7.6), (21, 43, 25, 78)]

prices = []

for row in data_sample[1:]:  # get a subset of a list, removing the first element: (1, 2, 3, 5, 12)
    prices.append(row[2])  # from the new list, add the third element: row[2]

print(prices)
# result: [6, 6.5, 25]

print(sum(prices))
# result: 37.5

Now, it is easier to understand what was done, the code is similar to the previous one, only it was used a feature called "list comprehensions":

def calculate_sum_succinct(data_sample):
    prices = [float(row[2]) for row in data_sample[1:]]  # is the same loop above, but using 'list comprehensions'
    return sum(prices)


data_sample = [(1, 2, 3, 5, 12), (4.4, 5.5, 6, 7),
               (0, 2.4, 6.5, 7.6), (21, 43, 25, 78)]

result = calculate_sum_succinct(data_sample)

print(result)
# result: 37.5