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.
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].