Lists
List operations
Slice a list to get part of it.
Operations on lists:
- Concatenation with + joins two lists into a new list: ['Red', 'Green'] + ['Blue'] gives ['Red', 'Green', 'Blue']. The original lists do not change. Both sides must be lists: joining a list and a string with + gives a TypeError.
- Repetition with *: ['Hi'] * 2 gives ['Hi', 'Hi'].
- Membership with in and not in: 'Green' in ['Red', 'Green', 'Blue'] is True.
Slicing works exactly as for strings. For nums = [5, 10, 15, 20, 25, 30]:
- nums[1:4] gives the elements at indices 1, 2 and 3: [10, 15, 20]. It stops just before index 4.
- A missing first index means from the start; a missing second one means to the end.
- An index that is too big is cut to the end of the list.
- If the first index is greater than the second, the result is an empty list, [].
- A third value gives the step: nums[0:6:2] gives [5, 15, 25].
- Negative indices and steps work too: nums[::-1] gives the list reversed, [30, 25, 20, 15, 10, 5], as a new list.
+ joins, * repeats, [n:m] slices.
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.