Exercise 4-5 Solution Python Crash Course Chapter 4: Working With Lists

 

📘 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:

  1. 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). The list() function converts this range into a list, which is stored in the variable num.

  2. Find the minimum value:

    The min() function is used to find the smallest number in the num list, which is expected to be 1.

  3. Find the maximum value:

    The max() function is used to find the largest number in the num list, which is expected to be 1,000,000.

  4. Calculate the sum:

    The sum() function is used to calculate the total of all numbers in the num 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:


🔗 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

Previous Post Next Post

Contact Form