Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,148 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