Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

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]
 
PREVIOUS NEXT
Tagged: #adding #multiple #items #list #python
ADD COMMENT
Topic
Name
5+1 =