FAQ: Code Challenge: Loops - Exponents

#1

This community-built FAQ covers the “Exponents” exercise from the lesson “Code Challenge: Loops”.

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

Computer Science

FAQs on the exercise Exponents

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!

#2

This is the function I used here, it returned ‘None’. But why is it wrong? Why do I need a second line to return new_lst, why can’t I combine it in one step?
I feel like I’m missing(or forgot) some basic knowledge which would make this clear to me.

def exponents(bases, powers):
new_lst =
for base in bases:
for power in powers:
return new_lst.append(base ** power)

print(exponents([2, 3, 4], [1, 2, 3]))

#3

Next time try using the </> symbol for code so that it keeps the indentation.

I think this is what you have?

def exponents(bases, powers):
  new_lst = []
  for base in bases:
    for power in powers:
      return new_lst.append(base ** power)

print(exponents([2, 3, 4], [1, 2, 3]))

.append() is a method which performs an action toward new_lst and doesn’t return anything.

I think you want to .append() the list after the powers in powers loop (where it is at now) but not return it. At the end after the list is created (after both for loops) then return the new_lst .

Here is an example of what you tried to do:

x = []
x.append(1)
y = x.append(2)

print(x)
print(y)

Returns

>>> [1, 2]
>>> None

See how y returns None? That is because .append() doesn’t return a value, but it still performed the action to append x. That’s kind of what you tried to do in your code.

1 Like
#4

Thank you for the tip, I didn’t realise my code would be copied as flat text, but you did get the code right!

And thanks for the example, I do understand that one. In your example y gets ‘None’ because the 2 get appended to x, leaving y without any value, right?
So for mine, I first have to state new_lst.append() before I can return it. If I don’t state that first, it doesn’t have anything to return yet, since it was getting appended after I typed return. Is that making sense?

#5

No, not really. .append() performs an action on an already existing list. It modifies the list in place instead of of returning a new list. You’re .append() is acting on the list you specify to make the addition to it.

Here’s a hopefully not confusing analogy. It’s like having a basket with one red apple. When we say basket.append(green apple) it’s an action that places a green apple in the basket. It doesn’t create a new basket, it doesn’t report what’s now in the basket. It’s purely the action. It’s putting that green apple in the basket.

So when you ask the action what it physically is or ask the action to report itself. It isn’t physically anything (isn’t data) . Thus it is None. It’s not a physical thing that reports or returns anything. It’s simply the action only. You can call the basket and see what is in after the action ( one red apple and one green apple) it because it is physical thing or actual data in the case above with the lesson.

That’s how I understand it.

1 Like
#6

Ooooh! Now I see, your analogy was really clear!!

I can’t return the basket.append(green apple). But after the green apple is put in there, I can return the basket to see what is in there now. I was trying to do it during the action, but I needed to look inside the basket afterwards, and not at the action itself.

2 Likes
#7

Something else of note that is not immediately obvious, list.append() has no return, so when we,

return my_list.append()

all that is seen by the caller is nothing.

>>> def add_to_list(my_list=[]):
	return my_list.append('a')

>>> add_to_list()
>>> 
1 Like
#8

Thank you monochromaticmau for your explanation and thank you Roy, it was so simple. I didn’t think that there was a difference to declare variable inside or outside the loop. Now, it’s clear for me. I was confused because I tested my fuction with IDLE and also http://pythontutor.com/visualize.html#mode=edit
and in both cases, they didn’t show me the mistake. The result was good…so, it was not easy to understand. Thank you guys !

#9

Hi everybody,

I tried that but I have a wrong answer:
< exponents([2, 3, 4], [1, 2, 3]) should have returned [2, 4, 8, 3, 9, 27, 4, 16, 64] , and it returned [2, 4, 8, 3, 9, 27, 4, 16, 64, 2, 4, 8, 3, 9, 27, 4, 16, 64, 2, 4, 8, 3, 9, 27, 4, 16, 64]/>

with these lines of code:

<>
new_lst =
def exponents(bases, powers):
for num in bases:
for exp in powers:
new_lst.append(num ** exp)
return new_lst
</>

return new_lst is same indentation than for num in bases

How do you use </> you put “p” inside or something else?

Thx

#10

you are missing a “/” on the top one.

#11

for num in bases it will first go through 2, then 3 then 4
for exp in powers it will then go to 1, 2, 3 for each of the above.

for num in bases it will first see 2.
for exp in powers it will loop through each one of the values in the list [1, 2, 3].
2 ** 1
2** 2
2** 3

After that it goes back up to for num in bases and then go to 3 then goes down to for exp in powers and does the same thing it will loop through the list [1, 2, 3]

3 ** 1
3 ** 2
3 ** 3

This is why you are getting each number in bases to each number in exp, in the way you are writing the code.

If you want the 0 index in bases to ** with 0 index of powers, then I would use indexes. I’m sure this is not the only way to do it, but that’s my suggestion.

#12

Be sure to define the new list inside the function else it doesn’t get reset with each call made, but keeps growing.

def func(foo, bar):
    result = []
#13

is there a way to do this with list comprehension? Thanks

#14

Yes, comprehensions permit nested loops.

>>> def exponents(bases, powers):
    return [b ** x for b in bases for x in powers]

>>> print(exponents([2, 3, 4], [1, 2, 3]))
[2, 4, 8, 3, 9, 27, 4, 16, 64]
>>> 
#15

Ahhhh thank you. I had “new_lst = [base ** power for base in bases AND power in powers]”

“and” instead of “for”

Also, didn’t even occur to me that I didn’t need a variable. Thanks for your help

1 Like
#16

You’re welcome. Now add to the challenge so that the result looks like,

[ [2, 4, 8], [3, 9, 27], [4, 16, 64] ]

Later…

Have you given this any consideration? It might help to know that as we can write a comprehension on two lists (or dictionaries) and use nested loops to yield two values, we can also write a comprension on a comprehension that still yields two variables, but also lets us group the results according to one of the variables.

#17

Hi. Could someone please explain why this code results in a SyntaxError?

def exponents(bases, powers):
	new_lst = []
	for i in range(len(powers)):
		i = range(len(bases[0:]) ** powers[i]
		new_lst.append(i)
	return new_lst
#18

When you see a syntax error in Python thrown on a line that you know to be correct, look to the preceding line for a missing close-quote or close-parentheses.

#19

Whoops. Thanks for the help. Fixed the mistake, but now I’m getting a “TypeError: unsupported operand type(s) for ** or pow(): ‘range’ and ‘int’”.

def exponents(bases, powers):
	new_lst = []
	for i in range(len(powers)):
		i = range(len(bases[0:])) ** powers[i]
		new_lst.append(i)
	return new_lst
#20

What you want to happen in the first line of the ‘for’ block isn’t going to work. range() does not work that way. I think you mean for every integer in the range() to be raised to a power. Although you could find some functionality close to that using NumPy, it won’t work in native Python. You will need to retrieve each item in range() (just as you do in the ‘for’ loop) to work with individually.

Hint 1: You’ll need a nested ‘for’ loop.

Hint 2: Because of Python’s magic ‘in’ operator, you don’t need any indexes (or range()) at all!

lst = ['a', 'b', 'c']

for idx in range(len(lst)):
    print(lst[idx], end = " ")
    
print()

for item in lst:        # no indexes!
    print(item, end = " ")

# Output:
a b c 
a b c
1 Like