pyhton list append code example

Example 1: 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 2: python how to append to a list

# Basic syntax:
your_list.append('element_to_append')

# Example usage:
your_list = ['a', 'b']
your_list.append('c')
print(your_list)
--> ['a', 'b', 'c']

# Note, .append() changes the list directly and doesn’t require an 
#	assignment operation. In fact, the following would produce an error:
your_list = your_list.append('c')

Example 3: 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"]
#

Example 4: opython append list

list.append(item)