0
0
NumPydata~30 mins

NumPy array vs Python list performance - Hands-On Comparison

Choose your learning style9 modes available
NumPy array vs Python list performance
📖 Scenario: You want to understand how fast NumPy arrays are compared to regular Python lists when doing math operations on many numbers. This helps you choose the best tool for your data tasks.
🎯 Goal: You will create a Python list and a NumPy array with the same numbers, then measure and compare the time it takes to add 1 to every number in each.
📋 What You'll Learn
Create a Python list with numbers from 0 to 9999
Create a NumPy array with numbers from 0 to 9999
Measure the time to add 1 to every element in the Python list using a loop
Measure the time to add 1 to every element in the NumPy array using vectorized addition
Print both times to compare performance
💡 Why This Matters
🌍 Real World
Data scientists often need to process large amounts of numbers quickly. Knowing that NumPy arrays are faster than Python lists helps them write efficient code.
💼 Career
Understanding performance differences between data structures is important for roles like data analyst, data engineer, and machine learning engineer to optimize data processing.
Progress0 / 4 steps
1
Create a Python list and a NumPy array
Create a Python list called py_list with numbers from 0 to 9999 using range(10000). Then import NumPy as np and create a NumPy array called np_array from py_list.
NumPy
Need a hint?

Use list(range(10000)) for the Python list and np.array() to convert it to a NumPy array.

2
Set up timing variables
Import the time module. Create two variables called start_time_list and start_time_np to store the start times for timing the Python list and NumPy array operations.
NumPy
Need a hint?

Use import time and create variables with initial value 0 to hold start times.

3
Measure time to add 1 to each element
Use time.time() to set start_time_list. Then create a new list result_list by adding 1 to each element in py_list using a for loop. Next, use time.time() to get end_time_list. Repeat timing for NumPy array addition by setting start_time_np, adding 1 to np_array with np_array + 1 saved as result_np, and getting end_time_np.
NumPy
Need a hint?

Use time.time() before and after each operation to measure elapsed time. Use a for loop to add 1 to each list element. Use np_array + 1 for NumPy.

4
Print the timing results
Calculate the elapsed time for the Python list as end_time_list - start_time_list and for the NumPy array as end_time_np - start_time_np. Print both times with clear messages: print(f"Python list addition took: {list_time} seconds") and print(f"NumPy array addition took: {np_time} seconds").
NumPy
Need a hint?

Subtract start times from end times to get elapsed seconds. Use print() with f-strings to show results.