Twine Quiz and Python Lists
When it is time to take the quiz, the Quiz Code will be written on the board. Enter the quiz code in the text field below and click "Submit".
Store, access, and change collections of data.
Watch this video to learn about Python lists.
A list is a Python data type that holds multiple items in a single variable. Items are ordered, changeable, and accessed by their position number (called an index).
# Creating lists team = ["Marcus", "Jake", "Deon", "Luis"] scores = [98, 85, 72, 100] empty = []
Lists use square brackets [ ] and items are
separated by commas. A list can hold strings, numbers,
booleans, or a mix of types.
Every item has an index. Indexing starts at 0, not 1.
team = ["Marcus", "Jake", "Deon", "Luis"] print(team[0]) # Marcus print(team[2]) # Deon print(team[-1]) # Luis (last item)
team[4] in a 4-item list) causes an IndexError.
The last valid index is always len(list) - 1.
Lists are mutable — you can modify them after creation.
team[1] = "Jordan" # team is now ["Marcus", "Jordan", "Deon", "Luis"]
team.append("Kai") # team is now ["Marcus", "Jordan", "Deon", "Luis", "Kai"]
team.insert(2, "Tyler") # Puts "Tyler" at index 2, shifts the rest right
team.remove("Deon") # Removes the first occurrence of "Deon"
team.pop(1) # Removes item at index 1 team.pop() # Removes the last item
| Code | What It Does |
|---|---|
| len(team) | Returns how many items are in the list |
| "Marcus" in team | Returns True if "Marcus" is in the list |
| team.sort() | Sorts the list in place (alphabetical or numerical) |
| team.reverse() | Reverses the order of items |
| team.count("Jake") | Counts how many times "Jake" appears |
| team.index("Deon") | Returns the index of the first "Deon" |
| team.clear() | Removes all items from the list |
Use a for loop to do something with every item in a list:
for player in team: print(player + " is ready!")
The loop variable (player) takes on each value in the list,
one at a time, from first to last.
| Syntax | Meaning |
|---|---|
| my_list = [a, b, c] | Create a list with items a, b, c |
| my_list[i] | Get item at index i (starts at 0) |
| my_list[-1] | Get the last item |
| my_list[i] = x | Change item at index i to x |
| my_list.append(x) | Add x to the end |
| my_list.insert(i, x) | Insert x at index i |
| my_list.remove(x) | Remove first occurrence of x |
| my_list.pop(i) | Remove & return item at index i |
| len(my_list) | Number of items |
| x in my_list | Check if x exists in list |
| for item in my_list: | Loop through every item |