my_list = ['a']
# You can use list.append(value) to append a single value:
my_list.append('b')
# my_list should look like ['a','b']
# and list.extend(iterable) to append multiple values.
my_list.extend(('b','c'))
# my_list should look like ['a','b','c']
fruits = ["apple","charry","orange"]
fruits.extend(("banana","guava","rasbarrry"))
print(fruits)
Mylist = [1, 2, 3]
#Appends multiple items using a list
Mylist += [4, 5]
#Mylist should be [1, 2, 3, 4, 5]
When we want to add multiple items to a list, we can use + to combine two
lists (this is also known as concatenation)
# here is an example of items sold at a bakery called items_sold:
items_sold = ["cake", "cookie", "bread"]
# Suppose the bakery wants to start selling "biscuit" and "tart":
# we will now create a new variable called items_sold_new
items_sold_new = items_sold + ["biscuit", "tart"]
print(items_sold_new)
# This Would output:
['cake', 'cookie', 'bread', 'biscuit', 'tart']
# We can inspect the original items_sold and see that it did not change:
print(items_sold)
#This Would output:
['cake', 'cookie', 'bread']
# We can only use + with other lists. If we type in this code:
my_list = [1, 2, 3]
my_list + 4
# we will get the following error:
TypeError: can only concatenate list (not "int") to list
# If we want to add a single element using +,
# we have to put it into a list with brackets ([]):
my_list + [4]