? Chapter 4 Practice Set
? Chapter 4 Practice Set
Explanation:
Pro Tip:
● Lists in Python are dynamic; you can append as many elements as you like!
Explanation:
Pro Tip:
● Sorting is useful when you need to rank or order data. Use reverse=True in the
sort() method to sort in descending order!
print(testing)
Explanation:
● Tuples are immutable in Python, meaning their elements cannot be changed after
creation.
● Attempting to modify any element of a tuple will raise a TypeError.
Pro Tip:
● Use tuples when you need a collection that should remain constant throughout the
program.
Explanation:
Pro Tip:
● sum() is highly optimized for summing numbers in Python lists, making it preferable
over manual loops.
Explanation:
Pro Tip:
● The count() method works on both tuples and lists to count specific elements.
● The max() function is used to find the largest number in the list.
● The result is printed in a formatted string.
Pro Tip:
● max() and min() are fast and effective for finding extremes in lists.
Explanation:
Pro Tip:
Explanation:
● We check if the number is prime by testing divisibility from 2 to the square root of the
number.
● The result is printed to indicate whether the number is prime.
Pro Tip:
● Checking divisibility up to the square root of the number reduces the number of iterations
and improves efficiency.
Explanation:
Pro Tip:
● Recursive functions are elegant but be cautious with large inputs due to potential stack
overflow.
💡 10. Write a program to create a dictionary from two lists.
keys = ['name', 'age', 'city'] # List of keys
values = ['Alice', 25, 'New York'] # List of values
Explanation:
● We use the zip() function to pair keys and values and create a dictionary.
● The dictionary is printed.
Pro Tip:
● zip() is a versatile function that can combine multiple iterables into tuples.
📝 Additional Questions:
1. What is a list comprehension? Provide an example.
2. Explain the difference between a list and a tuple.
3. How do you handle exceptions in Python? Give an example.
4. What are lambda functions? Provide a simple use case.
5. Explain the concept of decorators in Python with an example.