Your Page Title
🔍

    Convert Python List to NumPy Arrays

    What is a NumPy Array?

    A NumPy array (numpy.ndarray) is a data structure that stores elements of the same data type in a contiguous memory block. Unlike Python lists, NumPy arrays enable fast mathematical operations, less memory usage, and efficient computation.

    Advantages of Using NumPy Arrays Over Python Lists

    FeatureNumPy Array (ndarray)Python List
    PerformanceFast operations (vectorized)Slow (loops required)
    Memory EfficiencyUses less memoryUses more memory
    Data TypeHomogeneous (same type)Heterogeneous (mixed types)
    Mathematical OperationsSupported directlyRequires loops or map()
    ConvenienceRich set of built-in functionsLimited operations

    Step 1: Import NumPy

    Before using NumPy, install it using:

    pip install numpy

    Now, import it in Python:

    import numpy as np

    Step 2: Convert a Python List to a NumPy Array

    The numpy.array() function is used to convert a Python list into a NumPy array.

    Example 1: Converting a Simple List

    import numpy as np
    
    # Define a Python list
    my_list = [1, 2, 3, 4, 5]
    
    # Convert list to NumPy array
    np_array = np.array(my_list)
    
    print(np_array)
    print(type(np_array))  # Checking the type

    Output:

    [1 2 3 4 5]
    <class 'numpy.ndarray'>

    Here, the Python list [1, 2, 3, 4, 5] is successfully converted into a NumPy array.

    Step 3: Converting a Nested List (2D List)

    A nested list (list of lists) can be converted into a 2D NumPy array.

    nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    np_2d_array = np.array(nested_list)
    
    print(np_2d_array)

    Output:

    [[1 2 3]
     [4 5 6]
     [7 8 9]]

    Here, the Python list is converted into a matrix-like NumPy array.

    Step 4: Specifying Data Type (dtype)

    NumPy automatically detects data types, but you can explicitly specify a data type using the dtype parameter.

    Example 1: Default Data Type

    arr = np.array([1, 2, 3])
    print(arr.dtype)  # NumPy automatically chooses int type

    Output:

    int64  # (or int32 on some systems)

    Example 2: Converting List Elements to Float

    arr_float = np.array([1, 2, 3], dtype=float)
    print(arr_float)
    print(arr_float.dtype)

    Output:

    [1. 2. 3.]
    float64

    All elements are converted to floats.

    Example 3: Converting List Elements to Strings

    arr_str = np.array([1, 2, 3], dtype=str)
    print(arr_str)
    print(arr_str.dtype)

    Output:

    ['1' '2' '3']
    <U1  # Unicode string type

    All elements are converted to strings.

    Step 5: Converting Different Types of Lists

    Example 1: List with Mixed Data Types

    mixed_list = [1, 2.5, 3, 4.8]
    np_array = np.array(mixed_list)
    
    print(np_array)
    print(np_array.dtype)

    Output:

    [1.  2.5 3.  4.8]
    float64

    Since the list contains both integers and floats, NumPy converts all elements to float64 (upcasting).

    Example 2: Converting a List of Strings to Integers

    str_list = ['1', '2', '3']
    np_array = np.array(str_list, dtype=int)  # Convert to integers
    print(np_array)

    Output:

    [1 2 3]

    The string elements are converted to integers.

    Step 6: Memory and Performance Comparison

    NumPy is faster and more memory-efficient than Python lists.

    Memory Usage Comparison

    import sys
    
    py_list = list(range(1000))
    np_array = np.array(py_list)
    
    print("Python List Size:", sys.getsizeof(py_list))
    print("NumPy Array Size:", sys.getsizeof(np_array))

    Output (approximate values):

    Python List Size: 8056 bytes
    NumPy Array Size: 4096 bytes

    NumPy arrays take less memory than Python lists.

    Performance Comparison

    import time
    
    # Python List Multiplication
    py_list = list(range(1000000))
    start = time.time()
    py_list = [x * 2 for x in py_list]
    end = time.time()
    print("Python List Time:", end - start)
    
    # NumPy Array Multiplication
    np_array = np.array(range(1000000))
    start = time.time()
    np_array = np_array * 2  # Vectorized operation
    end = time.time()
    print("NumPy Array Time:", end - start)

    Output (approximate):

    Python List Time: 0.25 sec
    NumPy Array Time: 0.005 sec

    NumPy operations are 50x faster due to vectorized computation.

    Step 7: Converting a NumPy Array Back to a Python List

    To convert a NumPy array back to a list, use .tolist().

    np_array = np.array([1, 2, 3, 4, 5])
    py_list = np_array.tolist()
    print(py_list)

    Output:

    [1, 2, 3, 4, 5]

    Final Summary

    ConversionCode Example
    List → NumPy Arraynp.array([1, 2, 3])
    Nested List → 2D NumPy Arraynp.array([[1, 2], [3, 4]])
    Specify Data Typenp.array([1, 2, 3], dtype=float)
    Convert Back to Listnp_array.tolist()

    Conclusion

    • NumPy arrays are faster and more memory-efficient than Python lists.
    • Use numpy.array() to convert a list to a NumPy array.
    • Specify dtype for better control over data types.
    • NumPy supports vectorized operations, making calculations much faster.