pop( index )

>>> names = ["Bashar", "Ahmad", "Mustafa"]
>>> name_1 = names.pop()
>>> name_1
'Mustafa'
>>> names
["Bashar", "Ahmad"]
>>> name_2 = names.pop(0)
>>> name_2
'Bashar'
>>> names
['Ahmad']
>>> names.pop()
'Ahmad'
>>> names
[]

Shopping List – Take 4

Updating our shopping list with a removing-items feature.


# [shopping_list_4]:
shopping_list = []

def show_help():
  print("\nSeparate each item with a comma.")
  print("Type DONE to quit, SHOW to see the current list, and HELP to get this message, REMOVE to remove an item from the list.")
  
def show_list():
  count = 1
  for item in shopping_list: 
    print(" {}: {}".format(count, item))
    count += 1
    
def remove_item(idx):
  index = idx - 1 
  item = shopping_list.pop(index)
  print("Remove {}.".format(item))

    
print("Give me a list of things you want to shop for.")
show_help()

while True:
  new_stuff = input("> ")
  
  if new_stuff == 'DONE': 
    print("\nHere's your list: ")
    show_list()
    break
  elif new_stuff == 'HELP':
    show_help()
    continue
  elif new_stuff == 'SHOW':
    show_list()
    continue
  elif new_stuff == 'REMOVE':
    show_list()
    idx = input("Which item? Tell me the number.")
    remove_item(int(idx))
    continue
  else: 
    new_list = new_stuff.split(",")
    index = input("Add this at a certain spot? Press enter for the end of the list, "
                  "or give me a number. Currently {} items in the list.".format( 
        len(shopping_list)))
    if index:
      spot = int(index) - 1
      for item in new_list:
        shopping_list.insert(spot, item.strip())
        spot += 1
    else:
      for item in new_list:
        shopping_list.append(item.strip())
 

EXERCISE: Manipulating Lists

# 1. Move 1 to the beginning of the list
# 2. Remove non-numerical items
# 3. Now, make the_list contain only the numbers 1 through 20

the_list = ["a", 2, 3, 1, False, [1, 2, 3]]

# 1. Move 1 to the beginning of the list
the_list.insert(0, the_list.pop(3))

# 2. Remove non-numerical items
the_list.remove(False)
for item in the_list:
 try:
 item += 1
 except:
 the_list.remove(item)

# 3. Now, make the_list contain only the numbers 1 through 20
the_list.extend(list(range(4,21)))

print("the_list = {}".format(the_list))

OUTPUT:

the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]