I would like to define an empty list, then add items to the list. Does python 2.6 or 2.7, which I run, support this and what is the syntax? Thanks, My real name is Sigurd
Something like newlist = []
you can add items to a list, including an empty list, using new_list.append() the argument you put in the ( ) will be added as the next entry in the list.
I am struggling with this question on CodeAcademy Write a for loop that populates square_list with items that are the square (x ** 2) of each item in start_list. I tried this: start_list = [5, 3, 1, 2, 4] square_list = start_list for number in square_list: square = number **2 square_list.append(square) print square_list What I don't get is how you populate one array from another one.
yes, that one got me at first too :) You have to pull FROM the start_list to get the numbers that are then squared. Try this: for number in start_list: square = number**2 square_list.append(square)
I did do that first and it told me square_list is not defined, so I did this: start_list = [5, 3, 1, 2, 4] square_list = start_list for number in square_list: square = number **2 square_list.append(square) print square_list --It goes on and on!
you can define square_list like this: square_list = [] Then do the for loop with "for number in start_list:"
that will step through each of the 5 numbers in start_list, and inside the for loop, it will square them each and assign them to "square"... your append statement is fine. The only problems I see are 1) you need to modify the step where you set square_list = start_list... instead, set it equal an empty list like "square_list = [ ]" and 2) your for loop needs to be "for number in start_list"
Bingo! That did it. Many Thanks JakeV8. It was that darn for number part that I read a dozen times but never saw my error. It worked for real, now we'll see if Codeacademy likes it! Thanks again. -dan
Glad to help! Hope it works!
also the list comprehension: square_list = [x**2 for x in start_list] it does the same thing, but more fun...or not.
@snark Thanks! I wasn't aware you could use the "for x in list" structure inside a list bracket, but that's pretty nice -- gets it all done in one line.
Join our real-time social learning platform and learn together with your friends!