Lists: many values in one variable
A string holds characters. A list holds values of any kind, in order, between square brackets and separated by commas. The items of one list may be of different types: [7, "pen", 2.5, True]. Items are numbered like the characters of a string, from zero: names[0] is the first item, and len(names) counts the items. Here is the big difference from strings: a list can be changed. The line names[1] = "Adam" replaces the second item. A thing that can be changed after it is made is called mutable. Remember Week 6: a string cannot be changed, so text[0] = "S" failed, but a list accepts the change. The index rules are the same: the last valid index is the length minus one.
| A | B | C | |
|---|---|---|---|
| 1 | Mona | Omar | Salma |
| 2 | 0 | 1 | 2 |
1names = ["Mona", "Omar", "Salma"] 2print(names[0]) 3print(len(names)) 4names[1] = "Adam" 5print(names)
Mona 3 ['Mona', 'Adam', 'Salma']
1items = [7, "pen", 2.5, True] 2print(len(items)) 3print(items)
4 [7, 'pen', 2.5, True]
Make a list of five things in your school bag, written on paper. Write the index under each item. Which index is the last? Then change the third item and write the new list.