1

Here i have list with product name and product price but i want to take only the products price from the list and calculate the total price of all products. How can i do it ?

For example i have a list:
all_products = ['food',1000,'pasta',500,'beer',400]
how can i do : 1000+500+400 = 1900

1 Answers1

1

Given the integers are located on the odd indices, you can sum a slice of values, like:

sum(all_products[1::2])

but it might be better to take a look where you merge the two, and try to avoid that. For example by generating a list of 2-tuples, etc. Using a "flat" structure like the above one is usually not a good idea.

We can also sum up the ints and floats in the list, like:

sum(p for p in all_products if isinstance(p, (int, floats)))

But this is still "unsafe", since it is possible not all integers/floats are prices.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Well the solution depends on every odd indexed element being a number which might not be a general case – Devesh Kumar Singh Jul 11 '19 at 14:24
  • @DeveshKumarSingh: well even filtering on numbers is not very safe. It would be better if it was a list of `Product`s for example, where we can fetch the `.price`. Since right now it is unsafe to assume all number-like objects are prices. – Willem Van Onsem Jul 11 '19 at 14:27
  • Yes but assuming it as a list of strings/numbers is much more closer than assuming it a list of objects – Devesh Kumar Singh Jul 11 '19 at 14:28
  • @DeveshKumarSingh: well it is probably better to solve the problem "upstream", and avoid that. Since this is Django, it might even be possible to `.aggregate(..)`/`.annotate(..)` so to shift the computation to the database level, which is more efficient as well. – Willem Van Onsem Jul 11 '19 at 14:34
  • Wow, I did not see the django tag – Devesh Kumar Singh Jul 11 '19 at 15:48