Working with Lists and Dictionaries
List operations
Take a slice of a list.
List operations:
- Concatenation (the + operator) joins lists into a new list: [1, 3, 5, 7, 9] + [2, 4, 6, 8, 10] gives [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]. The original lists do not change; to keep the result, assign it to a variable. Both operands must be lists: [1, 2, 3] + 'abc' gives a TypeError.
- Repetition (the * operator) repeats a list: ['Hello'] * 4 gives ['Hello', 'Hello', 'Hello', 'Hello'].
- Membership: in gives True if an element is in the list; not in gives True if it is not.
Slicing makes a new list from part of an existing one: list1[start:stop:step].
- It takes elements from index start up to, but not including, index stop.
- If start is missing it begins at 0; if stop is missing it goes to the end. A stop beyond the end is simply cut at the end.
- If start is greater than stop (with a positive step), the result is an empty list [], not an error.
- step picks every n-th element: list1[0:6:2] takes indices 0, 2, 4. Negative indices work too, and a step of -1 gives the list reversed: list1[::-1].
Traversing (visiting every element) a list:
- with a for loop over the items: for item in list1: print(item);
- or over the indices: for i in range(len(list1)): print(list1[i]). Here len(list1) gives the number of elements and range() produces 0 up to len(list1) - 1.
Example (new): with nums = [5, 10, 15, 20, 25, 30], nums[1:4] is [10, 15, 20], nums[:2] is [5, 10], nums[::3] is [5, 20], and nums[4:1] is the empty list [].
A slice stops just before the stop index.
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.