list and append in python code example

Example 1: python array append

my_list = ['a','b']  
my_list.append('c') 
print(my_list)      # ['a','b','c']

other_list = [1,2] 
my_list.append(other_list) 
print(my_list)      # ['a','b','c',[1,2]]

my_list.extend(other_list) 
print(my_list)      # ['a','b','c',[1,2],1,2]

Example 2: append to lists python

list = ['larry', 'curly', 'moe']
  list.append('shemp')         ## append elem at end
  list.insert(0, 'xxx')        ## insert elem at index 0
  list.extend(['yyy', 'zzz'])  ## add list of elems at end
  print list  ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
  print list.index('curly')    ## 2

  list.remove('curly')         ## search and remove that element
  list.pop(1)                  ## removes and returns 'larry'
  print list  ## ['xxx', 'moe', 'shemp', 'yyy', 'zzz']

Example 3: append to list python

list = ["a"]
list.append("b")

print(list)
["a","b"]

Example 4: python append to list

stuff = ["apple", "banana"]
stuff.append("carrot")
# Print to see if it worked
print(stuff)
# You can do it with a variable too
whatever = "pineapple"
stuff.append(whatever)
# Print it again
print(stuff)

Example 5: python list append

# Python list mutation, adding elements
history = ["when"]

# adds item to the end of a list
history.append("how")
# ["when", "how"]

# combine lists
history.extend( ["what", "why"] ) # works with tuples too
# or
history = history + ["what", "why"]
# ["when", "how", "what", "why"]

# insert at target position
history.insert(3, "where")
# ["when", "how, "what", "where", "why"]
#