Python Forum
Nested loops vs list comprehension - pls. help
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Nested loops vs list comprehension - pls. help
#1
Hi!

I have following task:

Quote:The following code cell will execute a nested loop that will deliver all possible combinations of the elements from the products_on_sale, sale_prices and quantities lists:

products_on_sale = ['Chair_Type_1', 'Chair_Type_2', 'Chair_Type_3', 'Chair_Type_4']
sale_prices = [100, 120, 135, 150]
quantities = [1000, 1500, 1300]

for chair_type in products_on_sale:
    for price in sale_prices:
        for quantity in quantities:
            print ([chair_type, price*quantity])
Use a list comprehension to obtain the same output. Store it in a variable called sales_revenue.

Now, what I did:

products_on_sale = ['Chair_Type_1', 'Chair_Type_2', 'Chair_Type_3', 'Chair_Type_4']
sale_prices = [100, 120, 135, 150]
quantities = [1000, 1500, 1300]

sales_revenue = [[chair_type, price * quantity] for chair_type in products_on_sale for price in sale_prices for quantity in quantities]
sales_revenue
My code isn't accepted by the learning platform (Udemy) although it's generally consistent. Please note, my code returns nested list of lists, whereas the code with nested loops returns just loose range of lists (see also outputs pasted below). I guess I should provide a solution where the result is identical like in nested loops. I have no access to the author of this task, I can only test the code. Error details of the test are not very sophisticated though:

Error details
'' != 'Chair_Type_1 100000\nChair_Type_1 150000\[963 chars]00\n'
Diff is 1057 characters long. Set self.maxDiff to None to see it.
I doubt if I can have any other approach for the list comprehension case as it seems it always returns a list (even with a range of sub-lists). But then what am I doing wrong? I asked ChatGPT for a help, but it gives me stupid answers with identical code like mine. I will be thankful for a solution.

For better understanding of the issue, this is what nested loops code returns:

['Chair_Type_1', 100000]
['Chair_Type_1', 150000]
['Chair_Type_1', 130000]
['Chair_Type_1', 120000]
['Chair_Type_1', 180000]
['Chair_Type_1', 156000]
['Chair_Type_1', 135000]
['Chair_Type_1', 202500]
['Chair_Type_1', 175500]
['Chair_Type_1', 150000]
['Chair_Type_1', 225000]
['Chair_Type_1', 195000]
['Chair_Type_2', 100000]
['Chair_Type_2', 150000]
['Chair_Type_2', 130000]
['Chair_Type_2', 120000]
['Chair_Type_2', 180000]
['Chair_Type_2', 156000]
['Chair_Type_2', 135000]
['Chair_Type_2', 202500]
['Chair_Type_2', 175500]
['Chair_Type_2', 150000]
['Chair_Type_2', 225000]
['Chair_Type_2', 195000]
['Chair_Type_3', 100000]
['Chair_Type_3', 150000]
['Chair_Type_3', 130000]
['Chair_Type_3', 120000]
['Chair_Type_3', 180000]
['Chair_Type_3', 156000]
['Chair_Type_3', 135000]
['Chair_Type_3', 202500]
['Chair_Type_3', 175500]
['Chair_Type_3', 150000]
['Chair_Type_3', 225000]
['Chair_Type_3', 195000]
['Chair_Type_4', 100000]
['Chair_Type_4', 150000]
['Chair_Type_4', 130000]
['Chair_Type_4', 120000]
['Chair_Type_4', 180000]
['Chair_Type_4', 156000]
['Chair_Type_4', 135000]
['Chair_Type_4', 202500]
['Chair_Type_4', 175500]
['Chair_Type_4', 150000]
['Chair_Type_4', 225000]
['Chair_Type_4', 195000]
And this is what my code with list comprehension returns:

[['Chair_Type_1', 100000],
 ['Chair_Type_1', 150000],
 ['Chair_Type_1', 130000],
 ['Chair_Type_1', 120000],
 ['Chair_Type_1', 180000],
 ['Chair_Type_1', 156000],
 ['Chair_Type_1', 135000],
 ['Chair_Type_1', 202500],
 ['Chair_Type_1', 175500],
 ['Chair_Type_1', 150000],
 ['Chair_Type_1', 225000],
 ['Chair_Type_1', 195000],
 ['Chair_Type_2', 100000],
 ['Chair_Type_2', 150000],
 ['Chair_Type_2', 130000],
 ['Chair_Type_2', 120000],
 ['Chair_Type_2', 180000],
 ['Chair_Type_2', 156000],
 ['Chair_Type_2', 135000],
 ['Chair_Type_2', 202500],
 ['Chair_Type_2', 175500],
 ['Chair_Type_2', 150000],
 ['Chair_Type_2', 225000],
 ['Chair_Type_2', 195000],
 ['Chair_Type_3', 100000],
 ['Chair_Type_3', 150000],
 ['Chair_Type_3', 130000],
 ['Chair_Type_3', 120000],
 ['Chair_Type_3', 180000],
 ['Chair_Type_3', 156000],
 ['Chair_Type_3', 135000],
 ['Chair_Type_3', 202500],
 ['Chair_Type_3', 175500],
 ['Chair_Type_3', 150000],
 ['Chair_Type_3', 225000],
 ['Chair_Type_3', 195000],
 ['Chair_Type_4', 100000],
 ['Chair_Type_4', 150000],
 ['Chair_Type_4', 130000],
 ['Chair_Type_4', 120000],
 ['Chair_Type_4', 180000],
 ['Chair_Type_4', 156000],
 ['Chair_Type_4', 135000],
 ['Chair_Type_4', 202500],
 ['Chair_Type_4', 175500],
 ['Chair_Type_4', 150000],
 ['Chair_Type_4', 225000],
 ['Chair_Type_4', 195000]]
Reply
#2
The code is correct, but they expect that you to print each element and not the representation of the list, which holds all elements.

products_on_sale = ["Chair_Type_1", "Chair_Type_2", "Chair_Type_3", "Chair_Type_4"]
sale_prices = [100, 120, 135, 150]
quantities = [1000, 1500, 1300]

sales_revenue = [
    [chair_type, price * quantity]
    for chair_type in products_on_sale
    for price in sale_prices
    for quantity in quantities
]

# they compare what is written to stdout
# before, the representation of the list was printed and the first line does not match
# [['Chair_Type_1', 100000],
# also the last line has two closing brackets

# this prints each element of sales_revenue
# no double bracket at the begin and end.
for elements in sales_revenue:
    print(elements)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
The exercise does not make sense! You are selling 4 different chairs at 4 different prices and each time in 3 different quantities?

So you sell Chair 1 at 4 different prices [100, 120, 135, 150] in 3 different quantities: quantities = [1000, 1500, 1300] then repeat that for the other chair types? Does not compute!

You are missing a quantity.

products_on_sale = ['Chair_Type_1', 'Chair_Type_2', 'Chair_Type_3', 'Chair_Type_4']
sale_prices = [100, 120, 135, 150]
quantities_sold = [1000, 1500, 1300, 1600]

for i in range(len(products_on_sale)):
    print(products_on_sale[i], sale_prices[i] * quantities_sold[i])

sales_revenue = [(products_on_sale[i], sale_prices[i] * quantities_sold[i]) for i in range(len(products_on_sale))]

for tup in sales_revenue:
    print(f'Sales revenue: {tup[0]} = {tup[1]}')

# or with a generator in case you had millions of data
sales_revenue_gen = ((products_on_sale[i], sale_prices[i] * quantities_sold[i]) for i in range(len(products_on_sale))
for tup in sales_revenue_gen:
    print(f'Sales revenue: {tup[0]} = {tup[1]}')
Reply
#4
(Mar-16-2025, 05:32 AM)Pedroski55 Wrote: The exercise does not make sense! You are selling 4 different chairs at 4 different prices and each time in 3 different quantities?
With courses from Udemy, I'm not surprised. Anyone can publish there. You can be unlucky and get a bad course.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
Thank you for your replies. I found expected answer in the course's resources. It is:

sales_revenue = filter(None, [print(chair_type, price * quantity) for chair_type in products_on_sale for price in sale_prices
                             for quantity in quantities])
By the way, I think I would try to code more practical case, like a list Chair 1 at Price 1, Chair 2 at Price 2 and Chair 3 and 4 at Price 3 (two types may have the same unit price, why not), each chair type multiplied by quantity. I think I would use dictionary where chairs and prices would be mapped:

products_on_sale = ['Chair_Type_1', 'Chair_Type_2', 'Chair_Type_3', 'Chair_Type_4']
quantities = [1000, 1500, 1300]

chair_price_map = {
    'Chair_Type_1': 100,
    'Chair_Type_2': 120,
    'Chair_Type_3': 135,
    'Chair_Type_4': 135
}

sales_revenue = [
    (chair_type, price, quantity, price * quantity)
    for chair_type, price in chair_price_map.items()
    for quantity in quantities
]

for entry in sales_revenue:
    print(entry)
Reply
#6
(Mar-17-2025, 09:47 AM)pbsleczkowski Wrote: I found expected answer in the course's resources. It is:

sales_revenue = filter(None, [print(chair_type, price * quantity) for chair_type in products_on_sale for price in sale_prices
                             for quantity in quantities])

First of all, the above snippet is horrible anti-pattern. print call inside of list comprehension is abuse of list comprehension for sake of creating one-liner. All items in the resulting list will be None and the filter function with None as first argument is non-sense in this case - it will return filter object, which is just an empty generator and you bind that filter object to name sales_revenue
That is clearly not what the assignment asks:

Quote:Use a list comprehension to obtain the same output. Store it in a variable called sales_revenue.

i.e. store the output in the vriable
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with nested loops robert5502001 7 5,186 Aug-01-2022, 06:26 AM
Last Post: stevensanders
  Count occurences in a string and add to a list using loops Leyo 4 2,725 Mar-11-2022, 03:52 PM
Last Post: Leyo
  sorting a list using unicodes acending order, no loops, no sort(), using recursion lrn2codee 14 9,935 Jun-23-2021, 07:33 PM
Last Post: deanhystad
  Input validation for nested dict and sorting list of tuples ranbarr 3 4,916 May-14-2021, 07:14 AM
Last Post: perfringo
  computing average in nested loops cap510 5 6,818 Sep-11-2020, 12:33 PM
Last Post: deanhystad
  nested looping with list cap510 2 2,733 Sep-10-2020, 04:51 AM
Last Post: cap510
  Capitalize first letter of names in nested loops student_of_python 9 6,813 Oct-27-2019, 07:51 AM
Last Post: Larz60+
  nested for loops to recursion ashkea26 4 4,635 Nov-02-2018, 05:00 PM
Last Post: ichabod801
  question about list comprehension adriaanNL 1 2,674 Sep-09-2018, 04:03 PM
Last Post: buran
  Nested loops in openCV JimmyJangle 1 5,648 Apr-17-2018, 04:10 AM
Last Post: Mekire

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020