Apply a Function to a List Practice Problem
This data science coding problem helps you practice Functions & Scope, apply a function to a list, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Functions & Scope.
- Problem ID: 80
- Problem key: 80-apply-a-function-to-a-list
- URL: https://datacrack.app/solve/80-apply-a-function-to-a-list
- Difficulty: easy
- Topic: Functions & Scope
- Module: Python Fundamentals
Problem Statement
# 🧩 Apply a Function to a List
---
### 🎯 Goal
Applying a transformation to every element of a list is one of the most common data science operations. This problem teaches you the **map pattern** — the conceptual foundation of `map()`, list comprehensions, and Pandas `.apply()`.
---
### 🔍 Supported Operations
| `operation` | Transformation |
|:------------|:--------------|
| `"double"` | multiply by 2 |
| `"square"` | multiply by itself |
| `"absolute"` | remove sign (absolute value) |
| `"square_root"` | √x (return as float) |
---
### 💻 Task
Implement `apply_to_list(numbers, operation)` using a loop (no `map()` or list comprehensions).
---
### 📥 Input
- `numbers`: list of numbers
- `operation`: string — one of `"double"`, `"square"`, `"absolute"`, `"square_root"`
### 📤 Output
- A new list with the transformation applied to each element
---
### 🧩 Starter Code
```python
def apply_to_list(numbers, operation):
"""
Apply a named transformation to every element in numbers.
Args:
numbers (list): Input numbers
operation (str): "double" | "square" | "absolute" | "square_root"
Returns:
list: Transformed list
"""
result = []
for num in numbers:
# 🧠 TODO: Check operation and apply the right transformation
# 🧠 TODO: Append the transformed value to result
pass
return result
```
---
### 💡 Example
```python
apply_to_list([1, 2, 3, 4, 5], "square")
# Expected: [1, 4, 9, 16, 25]
apply_to_list([-3, -1, 0, 1, 3], "absolute")
# Expected: [3, 1, 0, 1, 3]
```
---
### 🔑 Key Concepts
- For `"square_root"`, use `num ** 0.5` to return a float
- The pattern: build an empty list, loop, transform, append
- This is what `list(map(transform_fn, numbers))` does under the hoodStarter Code
def apply_to_list(numbers, operation):
"""
Apply a named transformation to every element in numbers.
Args:
numbers (list): Input numbers
operation (str): "double" | "square" | "absolute" | "square_root"
Returns:
list: Transformed list
"""
result = []
for num in numbers:
# 🧠 TODO: Check operation and apply the right transformation
# 🧠 TODO: Append the transformed value to result
pass
return result