Combining Lists
append( list )
>>> a_list = [1, 2, 3]
>>> a_list.append( [4, 5] )
>>> a_list
[1, 2, 3, [4, 5]]
list( [iterable] )
>>> my_list = list( range(10) )
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[ ] + [ ]
>>> my_list + [10, 11, 12]
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Extend and Insert
extend( list )
>>> our_list = list( range(1,4) ) >>> our_list [1,2,3] >>> our_list.extend( range(5,11) ) >>> our_list [1,2,3,4,5,6,7,8,9,10]
insert(index, list-item)
>>> alpha = list('acdf')
>>> alpha
['a','c','d','f']
>>> alpha.insert(1,'b')
>>> alpha.insert(4,'e')
>>> alpha
['a', 'b', 'c', 'd', 'e', 'f', 'e']
Shopping List – Take 3
split(“,”) strip( )
[shopping_list_3]:
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.")
def show_list():
count = 1 # Throwaway variable
for item in shopping_list:
print(" {}: {}".format(count, item))
count += 1
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
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())