[Help Understand] Loops 13 - Review Exercice

So, i got to the last part of this lesson, and went to the review. I understand what it asks, and tried to put my tought into code, but it got weird. Like reallz weird. And somehow it worked, well not 100% working, but it was accepted.
My question is, why it was accepted, and how should i do it better? Because i’m really stuck in the code, and at this moment i’m going to take a walk to clear my head.
This is the exercice/review

# Your code below:
single_digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
squares = []
for digit in single_digits:
  print(digit)
for num in single_digits:
  num_squared = num ** 2
  squares.append(num_squared)
  print(squares)
  cubes = [element **3 for element in single_digits]
  print(cubes)

I guess the 1st print is fine, and in the next one, it should just appear the last part of numbers. This - [0, 1, 8, 27, 64, 125, 216, 343, 512, 729].
So, why?
Thank You

Hi janeiro93!
I took a look at the exercise you were working on. Step 1 is to create a list of single digits, which you did. Can you think of an easier way to create this list? What if it was asking for a list from 0-100?
Next, you created a loop to print out each number in your list and then added an empty list for your squares. Both of these steps look great.
If you look at step 4, it says " Inside the loop that iterates through single_digits , append the squared value of each element of single_digits to the list squares ." You actually created a new loop, which isn’t going to break your code or anything, it can just be repetitive and messy. Then, you printed your squares within the loop, meaning it will print the list of squares that is calculated during each iteration, not the final list of squares.
Lastly, your list comprehension for cubes looks great, but remember - list comprehension is often used in place of loops. Your list is defined within a loop - does it make sense there? Or would it be better to define the list somewhere else?

2 Likes

Hey aelsewhere.
That was really helpfull. Just bz reading it, got a new idea that i will work on. And like you said, to get the result i was expecting i should change the

so it will not be inside of the loop, same for the list comprehension. This will make what i intended at the start of the code. But reading further what you’ve said, i made things messy and complicated a bit. So there should be an easier way to get this done. Will keep the work on, and try to manage that. Many thanks, this was a great help.

1 Like