📘 Python Crash Course – Chapter 4: Working With Lists – Exercise 4-5 Solution
Welcome to another solution from Python Crash Course by Eric Matthes.
📝 Exercise 4-5
Task:
Make a list of the numbers from one to one million,
and then use min() and max() to make sure your list actually starts at one and
ends at one million .
Also, use the sum() function to see how quickly Python can
add a million numbers
✅ Solution Code:
num=list(range(1,1000001))
print(f'min :{min(num)}')
print(f'max :{max(num)}')
print(f'sum : {sum(num)}')
🧠 Code Explanation:
This Python code demonstrates how to work with a large list of numbers and perform basic operations like finding the minimum, maximum, and sum of the list. Here's how it works:
-
Create a list of numbers:
The
range(1, 1000001)
function generates a sequence of numbers starting from 1 and ending at 1,000,000 (inclusive). Thelist()
function converts this range into a list, which is stored in the variablenum
. -
Find the minimum value:
The
min()
function is used to find the smallest number in thenum
list, which is expected to be 1. -
Find the maximum value:
The
max()
function is used to find the largest number in thenum
list, which is expected to be 1,000,000. -
Calculate the sum:
The
sum()
function is used to calculate the total of all numbers in thenum
list. This demonstrates Python's ability to handle large numerical computations efficiently.
This code showcases Python's built-in functions for performing basic operations on lists, even when the list contains a large number of elements.
🔍 Output:
min :1
max :1000000
sum : 500000500000
📚 Related Exercises from Chapter 4:
- ➤ Exercise 4-1 | Pizzas
- ➤ Exercise 4-2 | Animals
- ➤ Exercise 4-3 | Counting to Twenty
- ➤ Exercise 4-4 | One Million
- ➤ Exercise 4-5 | Summing a Million
- ➤ Exercise 4-6 | Odd Numbers
- ➤ Exercise 4-7 | Threes
- ➤ Exercise 4-8 | Cubes
- ➤ Exercise 3-9 | Cube Comprehension
- ➤ Exercise 4-10 | Slices
- ➤ Exercise 4-11 | My Pizzas, Your Pizzas
- ➤ Exercise 4-12 | More Loops
- ➤ Exercise 4-13 | Buffet
- ➤ Exercise 4-14 | PEP 8
- ➤ Exercise 4-15 | Code Review
🔗 Connect With Us:
“The only way to learn a new programming language is by writing programs in it.”
– Dennis Ritchie
📌 Tags: #Python #PythonCrashCourse #CodingForBeginners #LearnPython #PythonProjects #PythonTips #introducingLists