w3resource

NumPy: Test whether numpy array is faster than Python list or not

NumPy: Array Object Exercise-193 with Solution

Write a Numpy program to test whether numpy array is faster than Python list or not.

Sample Solution:

Python Code:

import time
import numpy as np 
SIZE = 200000 
list1 = range(SIZE)
list2 = range(SIZE)
arra1 = np.arange(SIZE)
arra2 = np.arange(SIZE)
start_list = time.time()
result=[(x,y) for x,y in zip(list1,list2)]
print("Time to aggregates elements from each of the iterables:")
print("List:")
print((time.time()-start_list)*1000)
start_array = time.time()
result = arra1 + arra2
print("NumPy array:")
print((time.time()-start_array)*1000)

Sample Output:

Time to aggregates elements from each of the iterables:
List:
72.64399528503418
NumPy array:
19.61684226989746

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to extract all the contiguous 4x4 blocks from a given random 12x12 matrix.
Next: Write a NumPy program to create two arrays with shape (300,400, 5), fill values using unsigned integer (0 to 255). Insert a new axis that will appear at the beginning in the expanded array shape. Now combine the said two arrays into one.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}