Working with Lists and Dictionaries
Lists
Read and change an element of a list.
A list is an ordered sequence that is mutable (it can be changed) and made of one or more elements. Unlike a string, which holds only characters, a list can hold elements of different types: integers, floats, strings, tuples, even other lists. Elements go inside square brackets, separated by commas.
- [2, 4, 6, 8, 10, 12] is a list of even numbers; ['a', 'e', 'i', 'o', 'u'] a list of vowels; [100, 23.5, 'Hello'] a list of mixed types.
- A list of lists is a nested list: [['Physics', 101], ['Chemistry', 202], ['Mathematics', 303]].
Accessing elements by index:
- Each element has an index, starting at 0 for the first, then 1, 2 and so on. Use square brackets: list1[0] is the first element.
- An index beyond the end gives an IndexError (list index out of range).
- The index can be any expression that gives an integer, such as list1[1+4], which is list1[5].
- Negative indices count from the right: list1[-1] is the last element, list1[-2] the one before it, and list1[-n] is the first, where n = len(list1). The last element can also be written list1[len(list1)-1].
Lists are mutable: you can change an element in place by assigning to its index. With list1 = ['Red', 'Green', 'Blue', 'Orange'], the statement list1[3] = 'Black' makes it ['Red', 'Green', 'Blue', 'Black'].
Example (new): with days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], days[1] is 'Tue', days[-1] is 'Fri', and days[-5] is 'Mon'. After days[2] = 'Holiday', the list becomes ['Mon', 'Tue', 'Holiday', 'Thu', 'Fri'].
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.