In this lab, you will create tools for storing and accessing data.
On this page, you will create a shopping list app.
Many computer applications—contact lists, playlists, calendars, reminders—involve manipulating lists of information using tools that search, sort, or change the items on the list. You've worked with lists before as you customized the gossip project.
["Señora", "Ms. C", "my cat", "Hannah", "Jake"]
[Señora, Ms. C, my cat, Hannah, Jake]. The items are positioned in the list in the order they appear in the text: "Señora" has index 1, "Ms. C" has index 2, and so on.
shoppingList = []
shoppingList ← []or
shoppingList = ["apples", "bread", "carrots", "rice", "pasta"]
shoppingList ← [apples, bread, carrots, rice, pasta]or
shopping list
to begin empty, and then the user will add
or insert
additional grocery items one at a time.)
An element is another name for an item in a list. (If the same value is in the list twice, that counts as two different elements.) Each element has a unique index (position) in the list.
Insert
puts the new item before the place you specify.Add
puts the item after the last existing item.Assigning a list to a variable lets you use one name to represent all the elements of a list as a unit.
shoppingList.insert(1, "tomatoes")
(In Python, the first item of a list is item number 0, so the second item is in position 1.)
INSERT(shoppingList, 2, "tomatoes")or
shoppingList.append("tomatoes")
APPEND(shoppingList, "tomatoes")or
You've seen the ask
and answer
blocks on Unit 2 Lab 1 Page 2: Checking the Player's Guess.
You've worked with multiple sprites on Unit 1 Lab 2 Page 2: Making Programs Talk.
ask
the user for a new item, and then put the user's answer
in the grocery list.
You can also remove items from a list using . The
delete
block takes an item number and a list as input and it removes the item at that position from the list.
shoppingList.pop(1)
REMOVE(shoppingList, 2)or
item of
anywhere you can use any other expression. For example:
myFavoriteFood ← shoppingList[3]or
shoppingList[2] ← yourFavoriteFoodor
shoppingList[1] ← shoppingList[3]or
When you run this script in Snap!, the second line of code assigns to shopping list 2 the value of shopping list (that is, the same list, not a copy). So, the third line of code modifies both variables:
shoppingList2 ← shoppingListmakes a copy of the list. So modifying one of them does not modify the other.
The rules for how to use lists and how they behave differ depending on the programming language you are using.
shoppingList1 = ["apple", "banana"]
shoppingList2 = shoppingList1
shoppingList1.append("carrot")