Concept Flow - List indexing and slicing
Start with a list
Choose index or slice
If index: get single element
If slice: get sublist
Return result
End
You start with a list, pick an index or a slice, then get either one element or a sublist returned.
Jump into concepts and practice - no test required
my_list = [10, 20, 30, 40, 50] print(my_list[1]) print(my_list[1:4])
| Step | Expression | Evaluation | Result | Explanation |
|---|---|---|---|---|
| 1 | my_list[1] | Index 1 | 20 | Get element at index 1 (second element) |
| 2 | my_list[1:4] | Slice from 1 to 3 | [20, 30, 40] | Get elements from index 1 up to 4 (excluding 4) |
| 3 | my_list[-1] | Index -1 | 50 | Get last element using negative index |
| 4 | my_list[:3] | Slice from start to 2 | [10, 20, 30] | Get first three elements |
| 5 | my_list[3:] | Slice from 3 to end | [40, 50] | Get elements from index 3 to end |
| 6 | my_list[::2] | Slice with step 2 | [10, 30, 50] | Get every second element starting at index 0 |
| 7 | my_list[4:1:-1] | Slice backwards | [50, 40, 30] | Get elements from index 4 down to 2 in reverse |
| 8 | my_list[5] | Index 5 | Error | IndexError: index out of range, list has 5 elements (0-4) |
| 9 | my_list[1:10] | Slice from 1 to 9 | [20, 30, 40, 50] | Slice stops at list end, no error |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | After Step 5 | After Step 6 | After Step 7 | After Step 8 | After Step 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| my_list | [10, 20, 30, 40, 50] | [10, 20, 30, 40, 50] | [10, 20, 30, 40, 50] | [10, 20, 30, 40, 50] | [10, 20, 30, 40, 50] | [10, 20, 30, 40, 50] | [10, 20, 30, 40, 50] | [10, 20, 30, 40, 50] | [10, 20, 30, 40, 50] | [10, 20, 30, 40, 50] |
List indexing: my_list[index] gets one element. Negative index counts from end (-1 last). Slicing: my_list[start:end] gets sublist from start up to but not including end. Omitting start or end means from start or to end. Slices handle out-of-range gracefully; indexing does not. Use step in slicing: my_list[start:end:step].
my_list[2] return when my_list = [10, 20, 30, 40, 50]?my_list[0] is 10, my_list[1] is 20, and my_list[2] is 30.nums using indexing?-1 means the last element.nums[-1], which correctly accesses the last element. nums[1] accesses the second element. nums[last] is invalid syntax. nums[len(nums)] causes an IndexError because list indexes go from 0 to len(nums)-1.letters = ['a', 'b', 'c', 'd', 'e'] print(letters[1:4])
letters[1:4] means start at index 1 up to but not including index 4.nums = [1, 2, 3, 4, 5] print(nums[5])
nums has 5 elements with indexes 0 to 4.nums[5] causes an IndexError.data = [5, 10, 15, 20, 25, 30], which expression returns a new list with every second element in reverse order?data[::-2] starts from the end and takes every second element backwards.data[::-2] returns