script_6.py - List Slicing
Code
See script_6.py for full code.
Explanation
Line 8: data = list(range(0, 20))
- range(0, 20) generates numbers 0-19
- list() converts range object to actual list
- data is list of integers
Line 12: data[:5]
- Slice notation: [start:stop:step]
- Empty start means from beginning (index 0)
- Stop at index 5 (exclusive, so gets 0-4)
- Returns new list (doesn't modify original)
Line 13: data[-5:]
- Negative index -5 counts from end
- Empty stop means to end of list
- Gets last 5 elements
Line 17: data[::2]
- Empty start and stop = whole list
- Step 2 means every 2nd element
- Gets elements at indices 0, 2, 4, 6, 8...
Line 19: data[::-1]
- Step -1 means backwards
- Reverses the list
- Alternative to .reverse() method
Line 23: total_pages = (len(data) + PAGE_SIZE - 1) // PAGE_SIZE
- // is floor division (integer division)
- Calculates number of pages needed
- Formula rounds up: (20 + 5 - 1) // 5 = 24 // 5 = 4
Line 27-29: Pagination logic
- start = page_num * PAGE_SIZE calculates starting index
- end = start + PAGE_SIZE calculates ending index
- data[start:end] gets one page of data
- Slice handles out-of-bounds gracefully (last page may be smaller)
Line 35: window = data[i:i + WINDOW_SIZE]
- Sliding window pattern
- Fixed-size slice moves through list
- Used in time series, signal processing