Pretend that it’s Taco Tuesday and you need to come up with a shopping list so you can make tacos. After checking the kitchen, you come up with this list:
groceries = ['tortillas', 'meat', 'salsa', 'cheese', 'seasoning']
What if you forgot to add something to your shopping list? This is what makes a list a very useful data structure in Python. You can add information, delete information, and even reorder information. Below are nine useful methods for working with lists:
Append – Your family wants you to add vegetables, like lettuce, tomatoes, or onions. The append() method adds another item to the end of your list. Add vegetables to your list:
groceries.append('vegetables')
What do you think you will see if you print(groceries)
? Try it out!
Insert – Since lists are ordered, you shop for your ingredients in order. What if you want to add sour cream to your list but you want to get it after the salsa and before the cheese? To insert an item, you need to know the list position you want the new item to occupy. Tortillas currently hold position 0, so sour cream would occupy position 3.The code to insert cheese at this position is groceries.insert(3, 'sour cream')
. Note that the indices of all the following elements will be shifted by one. For example, seasoning used to be at position 4 but now it holds position 5:
groceries = ['tortillas', 'meat', 'salsa', 'sour cream', 'cheese', 'seasoning', 'vegetables']
Delete – Deleting an item from the list can be done with the del
command. Like insert()
, you need to know the index of the element that you want to delete. You find out that you already have cheese, so you remove it from the list with del groceries[4]
. Note that the index of any following elements will shift down by one.
Remove – What if you did not know the index of the value you wanted to remove? Maybe your grocery list was too long and you could not find cheese on the list. Using groceries.remove('cheese')
deletes the item without needing to know the index. Make sure you spell it right! If the list cannot find the value, it will not delete anything.
Length – You are now ready to checkout and you want to know if you can go into the express line, which only serves customers with 12 or fewer items. You’re in a hurry and you don’t want to count all of the items one by one. len()
returns the number of items in your list.
print(len(groceries))
You can also assign this value to a variable and use it to automate whether or not you can go into the express line using an if statement:
num_items = len(groceries)
if (num_items < 13):
print("Go to the express line!")
else:
print("You have more than 12 items. No express line for you :(")
Clear – You arrive home from grocery shopping with everything you need so you want to empty your list. The clear()
method removes all of the items from the list at once. You empty the list with groceries.clear()
so that it’s ready for another Taco Tuesday.