Learn › Class 11 › Computer Science / Informatics Practices › Lists, tuples, dictionaries
Lists, tuples and dictionaries
You will learn to
- Create, index and slice lists and tuples
- Use common list and dictionary methods
- Choose between a list, a tuple and a dictionary
- Traverse each collection with a loop
Helpful to know first: Python fundamentals.
A list is an ordered, changeable collection written in square brackets, such as [10, 20, 30]. Indexes start at 0, and −1 means the last item. A slice L[a:b] gives items from index a up to, but not including, b.
Useful list methods include append(), extend(), insert(), pop(), remove() and sort(). The + operator joins lists, and * repeats them. len() gives the number of items.
A tuple is ordered but cannot be changed after it is made. It is written in round brackets, such as (3, 4). A tuple with one item needs a comma: (5,).
A dictionary stores key–value pairs, such as {'roll': 12, 'name': 'Asha'}. Keys must be unique and immutable. d[key] reads a value, and d.get(key, default) avoids an error when the key is missing.
Looping through collections
for x in L visits each list item. for k in d visits each key. for k, v in d.items() gives each key with its value.
Common mix-ups
Not quite: You can change a tuple with t[0] = 5.
Instead: Tuples are immutable, so this raises a TypeError. Make a new tuple instead.
Not quite: L.sort() returns the sorted list.
Instead: L.sort() sorts L in place and returns None. Use sorted(L) to get a new sorted list.