More with 'for'


So, I'm stuck on "More with 'for'", and I have been for an hour. I'm repeatedly getting the errors "can't assign literal", and "square_list should be the same length as start_list".

I've been checking pretty much all of the other topics before this, even copied a few, and I've gotta be royally screwing this up. Any solid help would be greatly appreciated.

What I have after all this time is:

start_list = [5, 3, 1, 2, 4]
square_list = []

Your code here!

for x in start_list:
for x in start_list:
for x in start_list:
for x in start_list:
for x in start_list:

print square_list



We would not use literals in our program. The variable is much more useful.

for x in start_list:              # iterate over the list
    square_list.append(x ** 2)    # append the squared value

print square_list


It seems that even changing them to the variables isn't making a difference in regards to list length. I'd really like to learn to code but I'd also like to not get caught up on seemingly simple problems.


The purpose of a for loop is to minimize or elliminate repetition. What you are attempting to do is counterproductive. We only need to run the loop once, and all the different values are generated in one pass. We're not really caught up in something simple, but rather something slightly abstract so we do not readily get the full picture until we look closer, and gain experience. Expect to run up against this a lot, and don't let it get your back up. Take it in stride and learn from it.


After some exasperated mashings of "reset code", I finally figured it out. The concept of variables was catching me up a bit. Thanks for explaining the loops and redundancy. It makes perfect sense in hindsight.


This all falls under one umbrella... Re-usability. The more we can abstract away repeated patterns into generic utilities, the clearer the gist of our program becomes. Maintenance is much simpler, especially when it comes to debugging changes made months later.

It starts with factoring. Similar to math, it is taking one piece of code that appears in more than one location and assigning it to its own object, then refer to the object in each instance that it is removed from. This is where variables, functions and classes fit in. Just as the code inside the loop was re-used x times, a function can be used any number of times, and be given discrete data in each call.

Re-factoring is a similar analysis that examines code deterministically. But that is another story I'm still fledgling at, so won't cross into that territory, just yet. Still, it's on the table now so add it to the to learn list.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.