Hello!
I was working on this exercise: https://www.codecademy.com/courses/learn-python-3/lessons/create-python-list/exercises/append-list
And I have a question. It may be dumb 
Why does
def add_order(new_orders):
orders = ["daisies", "periwinkle"]
for x in new_orders:
orders.append(x)
return orders
print(add_order(['tulips']))
print(add_order(['roses']))
return
['daisies', 'periwinkle', 'tulips']
['daisies', 'periwinkle', 'roses']
I heard that .append generally modifies the original array, so when calling add_order(['roses'])
, why it is not [‘daisies’, ‘periwinkle’, ‘tulips’, ‘roses’]?
It’s not a dumb question.
Roses is not part of the original list (orders).
You’re adding one item to the end of the original list. .append() only adds a single item or object at a time.
Ok. Thank you. Can you recommend what I should use to achieve my goal?
You could use the “+” sign to add new items.
Summary
def add_order(new_orders):
orders = ["daisies", "periwinkle"] + new_orders
return orders
print(add_order(['tulips', 'roses', 'daffodils']))
>>>['daisies', 'periwinkle', 'tulips', 'roses', 'daffodils']
If you didn’t want to write a function you could use .extend()
which adds all items from the iterable.
Summary
orders = ["daisies", "periwinkle"]
orders.extend(['tulips'])
orders.extend(['roses'])
print(orders)
>>['daisies', 'periwinkle', 'tulips', 'roses']
See:
https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
1 Like