append multiple strings to list python
>>> lst = [1, 2] >>> lst.append(3) >>> lst.append(4) >>> lst [1, 2, 3, 4] >>> lst.extend([5, 6, 7]) >>> lst.extend((8, 9, 10)) >>> lst [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> lst.extend(range(11, 14)) >>> lst [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Source: stackoverflow.com
adding multiple items to a list python
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]