Oct-09-2024, 08:41 PM
(This post was last modified: Oct-09-2024, 08:41 PM by deanhystad.)
Quote:Yes, I want the sequence {9, 8, 7, 6, 5, 4, 3, 2, 1}. Instead of coding for it by looping down from 9 to 1 I should just create the list my_list = [9, 8, 7, 6, 5, 4, 3, 2, 1]Would my_list always be [9, 8, 7, 6, 5, 4, 3, 2, 1]? If so, that would be a good way to build the list. If you want to build a list where the starting and ending numbers are not always the same, using range() is a good way to make a list.
my_list = list(range(9, 0, -1))Save append() for when there is some processing involved when adding items to a list. Be leery about using insert as it can be complicated to insert multiple values int a list (unless you are always inserting at the front). I usually make a new list instead of inserting items into an existing list. If you really want to use insert, insert the last value first and work your way back to the first value. That way you are inserting into the part of the list that has not been moved by other inserts.