Это не распечатает:
100
100
Вы инициализировали список с 1 элементом, размер этого списка равен 1. Однако ваш диапазон начинается с 1 для цикла for
, что на самом деле происходит:
price = 100 # assigns 'price' to 100
price = [price] # creates a 'price' list with 1 element: [100]
for i in range(1, 3): # The list is 0-indexed, meaning price[0] contains 100
print(price[0]) # prints 100 as it should
price[i] = price[i - 1] # i is 1, price[i] is not an assigned value, i.e: you never assigned price[1]
price.append(price[i]) # This doesn't execute because an exception was thrown
print(price[i]) # Neither does this
Чтобы получить результат, который вы ищете, это будет работать:
price = [100] # creates a 'price' list with 1 element: [100]
for i in range(0, 2): # Start at index 0
print(price[i]) # Print current index
price.append(price[i]) # Append current value of price[i] to the price list
Чтобы убедиться, что все добавлено, как вы ожидали, вы можете протестировать его с помощью len:
print(len(price))
Output:3
Тем не менее, это предпочтительный способ добавления, как показал @smci в своем ответе.