In the first example, we initialize my_list
with the values [10, 20, 30]
. To add 5
to each list element, we use a for
loop that iterates over the range of the list’s length. During each iteration, the loop updates the current element by adding 5
. This operation is performed in place, meaning each list element is individually modified. After the loop completes, the updated list is printed, resulting in [15, 25, 35]
. This approach shows how lists require explicit loops for element-wise operations, making them less efficient for bulk arithmetic operations.
In the second example, we use NumPy’s array
function to create an array my_array
with the same values [10, 20, 30]
. NumPy arrays support vectorized operations, which means we can perform arithmetic operations on the entire array directly without an explicit loop. By executing my_array + 5
, each array element is incremented by 5
in a single, efficient operation. The result [15, 25, 35]
shows how NumPy arrays facilitate concise and performant element-wise operations compared to traditional lists.
Is a Python list just an array?
No, a Python list is not the same as an array. Lists are more versatile because they can hold mixed data types and are part of the Python core. Arrays, conversely, are specialized data structures for numerical data and are not natively included in Python’s core libraries.
What is the advantage of using an array over the list?
Arrays offer better performance and memory efficiency than lists, especially when handling large datasets or performing numerical computations. For example, arrays are significantly faster in operations involving vectorization (applying operations element-wise without loops). Also, arrays have serious applications in machine learning’s computational-intensive algorithms.