简体   繁体   中英

Python, issue with for loop and List can't figure it out

This is from codecademy, it keeps telling me that square_list isn't the same length as start_list (it needs to be) and it also doesn't sort it even tho I am calling sort onto square_list (have to call it on square_list can't do it with start_list )

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

square_list.append(start_list)
square_list.sort()

for start_list in square_list:   
    print square_list

The append() function call in this case appends the entire list start_list to the square_list which would result in something like [[5, 3, 1, 2, 4]] . Use the + operator to concatenate the lists:

square_list = square_list + start_list

You can also create a list comprehension like this:

square_list = [n for n in start_list]

If you have to use the append() function, then do something like:

for n in start_list:
    square_list.append(n)

However, this isn't the pythonic way and list comprehensions are used to avoid something like this.

Q: Write a for-loop that iterates over start_list and .append()s each number squared (x ** 2) to square_list. Then sort square_list!

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

# loop start_list
for element in start_list:
    # append each element**2 to square_list
    square_list.append(element**2)
# sort the list.
square_list.sort()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM