FAQ: Learn Python: Loops - Nested Loops

This community-built FAQ covers the “Nested Loops” exercise from the lesson “Learn Python: Loops”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science
Data Science

FAQs on the exercise Nested Loops

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

3 posts were split to a new topic: I’m close, but its not working?

3 posts were split to a new topic: Why doesn’t my code work?

2 posts were split to a new topic: Unsupported types for adding?

5 posts were split to a new topic: How can I skip an index while iterating through a list?

6 posts were split to a new topic: How does += work?

hi, this is my version:

sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
scoops_sold=0
for location in sales_data:
  for element in location:
    element
    scoops_sold+=element
print(scoops_sold)
6 Likes

Suppose I wanted to obtain the sum total of the element(s) at each individual index position within the sub lists. Is there a way to create a nested loop that will obtain the desired results? I was able to work out this code but the loops were not nested. Just wondering what I’m missing and whether there is an easier way to produce the results.

sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]

scoops_sold = 0
scoopA =
scoopB =
scoopC =
scoops_sold_A = 0
scoops_sold_B = 0
scoops_sold_C = 0

for location in sales_data:
scoopA.append(location.pop(0))
scoopB.append(location.pop(-2))
scoopC.append(location.pop(-1))
for total_A_scoops in scoopA:
scoops_sold_A += total_A_scoops
for total_B_scoops in scoopB:
scoops_sold_B += total_B_scoops
for total_C_scoops in scoopC:
scoops_sold_C += total_C_scoops
print(scoops_sold_A, scoops_sold_B, scoops_sold_C)

output: 19 39 38

On the surface it should be a simple matter to work out the sums of the sublists. Anytime things get complicated means it is time to step back and examine the problem again.

If permitted, we could use the built in sum() function in a list comprehension…

scoops_by_flavor = [sum(x) for x in sales_data]

Let’s assume that comprehensions have not yet been taught. That means writing a more naive loop.

scoops_by_flavor = []
for x in sales_data:
    scoops_by_flavor.append(sum(x))

Now let’s assume that the sum() function is not on the table.

scoops_by_flavor = []
for x in sales_data:
    z = 0
    for y in x:
        z += y
    scoops_by_flavor.append(z)

The end result will be a list of sums.

[51, 15, 30]
2 Likes

I apologize, evidently I did not convey my question clearly. To be clear, I was looking for a way to sum the “columns”, not the “rows”, if you will. Ultimately I came across a couple of different ways to attack this problem, though the numpy meothod was out of the scope of the given exercise.

import numpy as np
sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
new_list = np.array(sales_data)
flavor_sum1 = np.sum(new_list, 0)
print(flavor_sum1)

sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
flavorsum2 = list()
for j in range(0, len(sales_data[0])):
count = 0
for i in range(0, len(sales_data)):
count = count + sales_data[i][j]
flavorsum2.append(count)
print(flavorsum2)

Thank you for your response! I apologize for not making my question clear in the first place.

If advanced tools are on the table, then unpacking and zip can be used.

a, b, c = sales_data

The above will unpack the three-member-sequence into three separate entities.

cols = zip(a, b, c)    # relative position transformation
sums = [sum(x) for x in cols]
print (sums)    #  [19, 39, 38]

Questions don’t have to be clear so long as the dialogue is open long enough to make them clear. It’s an inch by inch process that none of us should try to speed along.


When it comes to giving identities to objects, I prefer to do that at the end of a process, not before or during. It only complicates matters. Look for the process and funnel the data that way using iteration.

print ([sum(x) for x in zip(a, b, c)])

Yes, we did declare a, b, and, c, of necessity as part of the process. If we did this inside a function, they would be temporary and garbage collected.

def column_totals(data):
    a, b, c = data
    return [sum(x) for x in zip(a, b, c)]
print (column_totals(sales_data))

Not a single global variable is needed, save to keep the result afloat.


Going down the advanced tools rabbit hole, we can further pefect the above to take any size data object, not a fixed three. Introducing the splat operator…

>>> def column_totals(data):
    return [sum(x) for x in zip(*data)]

>>> s = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
>>> column_totals(s)
[19, 39, 38]
>>> s = [[12, 17, 22], [2, 10, 3], [5, 12, 13], [12, 18, 31]]
>>> column_totals(s)
[31, 57, 69]
>>> s = [[12, 17, 22, 9], [2, 10, 3, 11], [5, 12, 13, 8]]
>>> column_totals(s)
[19, 39, 38, 28]
>>> 

When we stretch this out into the most naive code, it is still very simple and does not need a lot of pigeon holes. Suggest visualize the objects passing through the process without going to the extra bother to name each and every one of them.

What’s the difference between “+=” and the way I did below:

sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]

scoops_sold = 0

for location in sales_data:
  #print (location)
  for element in location :
    scoops_sold = sum(sales_data[0]+sales_data[1]+sales_data[2])
    print(scoops_sold)

1 Like

location will be one of the three lists in sales_data.

element will be one of the three values in each subsequent location list.

At this point we can add the value to scoops_sold

scoops_sold += element

What the above is doing is concatenating all three lists into one list,

    [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
 => [12, 17, 22, 2, 10, 3, 5, 12, 13]

then passing that list to the sum() function.

>>> sum([12, 17, 22, 2, 10, 3, 5, 12, 13])
96

It rules out the need for any loops.

The logic is sound but it also is fixed and cannot adjust dynamically to more or less locations. The iterative approach can handle any number of locations.

3 Likes

Thanks a lot! That’s very clear!

1 Like

Hi for the question : 2.

Go through the sales_data list. Call each inner list location , and print out each location list.

I did: sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
scoops_sold = 0
for sales in sales_data:
for data in sales:
print([sales])

my answer was:
[[12, 17, 22]]
[[12, 17, 22]]
[[12, 17, 22]]
[[2, 10, 3]]
[[2, 10, 3]]
[[2, 10, 3]]
[[5, 12, 13]]
[[5, 12, 13]]
[[5, 12, 13]]

the correct answer was:
image

I now know the correct answer but help me understand why my logic was incorrect.

1 Like

Did you intend to print data?

Hi Roy, l intended to print the location list of all the data that was in the lists.

Hi Roy do you perhaps have a blog/Linkedin? You have a wealth of knowledge and understanding.

On the whole, a blog would not be a good fit for me since one stands correction as much as not. Here I am mingling with the beginner group and viewing their problems from the same perspective. We all get to be wrong, and find our way to the truth, as it were. Not something we can do with a blog.

Until I give up the ghost, this is where you find me.

3 Likes

2 posts were split to a new topic: Topic reversed Lists

This is my code- and l seem to be getting duplicates after the creation of transaction_clean =
I checked with the instructor’s code and everything is sound but my has duplicates
‘’’’’'daily_sales_replaced = daily_sales.replace(";,;"," - ")
print(daily_sales_replaced)

daily_transactions = daily_sales_replaced.split(",")
#print(daily_transactions)

#5
daily_transactions_split =
for transaction in daily_transactions:
daily_transactions_split.append(transaction.split(" - "))

print(daily_transactions_split)

#Everything above is correct

transactions_clean =
for transaction in daily_transactions_split:
transaction_clean =
for data_point in transaction:
transaction_clean.append(data_point.replace("\n"," “).strip(” "))
transactions_clean.append(transaction_clean)

print(transactions_clean)

customers =
sales =
thread_sold =

#11
for transaction in transactions_clean:
customers.append(transaction[0])
sales.append(transaction[1])
thread_sold.append(transaction[2])

total_sales = 0
for sale in sales:

total_sales += float(sale.strip("$"))

print(total_sales)’’’’

THE RESULTING DUPLICATE IS AS FOLLOWS: