Indexing and Slicing Lists Practice Problem
This data science coding problem helps you practice Lists & Basic Data Structures, indexing and slicing lists, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Lists & Basic Data Structures.
- Problem ID: 72
- Problem key: 72-indexing-and-slicing-lists
- URL: https://datacrack.app/solve/72-indexing-and-slicing-lists
- Difficulty: easy
- Topic: Lists & Basic Data Structures
- Module: Python Fundamentals
Problem Statement
# 🧩 Indexing and Slicing Lists
---
### 🎯 Goal
**Slicing** lets you extract a sub-section of a list in one clean expression. It's one of Python's most powerful features and the same syntax carries over to NumPy arrays, Pandas DataFrames, and PyTorch tensors.
---
### 🔍 Slicing Syntax
```python
lst[start:end] # Elements from index 'start' up to (but NOT including) 'end'
lst[:end] # From the beginning up to 'end'
lst[start:] # From 'start' to the end
lst[start:end:step] # Every 'step'-th element in the range
```
| Expression | Result (for `[10, 20, 30, 40, 50]`) |
|:-----------|:-------------------------------------|
| `lst[1:4]` | `[20, 30, 40]` |
| `lst[:3]` | `[10, 20, 30]` |
| `lst[2:]` | `[30, 40, 50]` |
| `lst[-3:]` | `[30, 40, 50]` |
| `lst[::2]` | `[10, 30, 50]` |
> 💡 Slicing **never raises an IndexError** — it just returns as many elements as it can.
---
### 💻 Task
Implement `slice_list(lst, start, end)` that returns the sub-list from index `start` to `end`. If `start` is `None`, slice from the beginning. If `end` is `None`, slice to the end.
---
### 📥 Input
- `lst`: list — the list to slice
- `start`: int or None — the start index
- `end`: int or None — the end index (exclusive)
### 📤 Output
- A new list containing the sliced elements
---
### 🧩 Starter Code
```python
def slice_list(lst, start, end):
"""
Return a sub-list from start to end (exclusive).
Args:
lst (list): The input list
start (int or None): Start index (None means from beginning)
end (int or None): End index, exclusive (None means to the end)
Returns:
list: The sliced sub-list
"""
# 🧠 TODO: Return the slice of the list from start to end
pass
```
---
### 💡 Example
```python
slice_list([10, 20, 30, 40, 50, 60, 70], 1, 5)
# Expected: [20, 30, 40, 50]
slice_list([10, 20, 30, 40, 50], -3, None)
# Expected: [30, 40, 50]
```
---
### 🔑 Key Concepts
- `lst[start:end]` returns a **new list** (original is unchanged)
- The `end` index is **exclusive** — the element at `end` is NOT included
- `None` in a slice means 'go to the boundary'
- Negative indices work in slices: `lst[-3:]` gets the last 3 elementsStarter Code
def slice_list(lst, start, end):
"""
Return a sub-list from start to end (exclusive).
Args:
lst (list): The input list
start (int or None): Start index (None means from beginning)
end (int or None): End index, exclusive (None means to the end)
Returns:
list: The sliced sub-list
"""
# 🧠 TODO: Return the slice of the list from start to end
pass