Numpy - Iterating Over Arrays Last Updated : 23 Jan, 2025 Comments Improve Suggest changes Like Article Like Report NumPy provides flexible and efficient ways to iterate over arrays of any dimensionality. For a one-dimensional array, iterating is straightforward and similar to iterating over a Python list.Let's understand with the help of an example: Python import numpy as np # Create a 1D array arr = np.array([1, 2, 3, 4, 5]) # Iterate over the array for ele in arr: print(ele) Output1 2 3 4 5 Explanation:Each element of the array is accessed sequentially, making iteration simple and intuitive.Let's explore various others ways to iterate over Arrays:Table of ContentIteration Over a Two-Dimensional ArrayIterating Over Higher-Dimensional ArraysUsing nditer Using Enumerate Using BroadcastingIteration Over a Two-Dimensional ArrayFor multidimensional arrays, iteration is performed over the first axis by default. Each iteration yields a one-dimensional sub-array. Python import numpy as np # Create a 2D array arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Iterate over rows for row in arr_2d: print(row) Output[1 2 3] [4 5 6] [7 8 9] Explanation:arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) creates a 2D array with three rows and three columns.for row in arr_2d: loops through each row of the 2D array, treating it as a separate one-dimensional array.For Element-Wise IterationTo iterate over individual elements of a 2D array, the array can be flattened using the .flat attribute. Python import numpy as np arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) for element in arr_2d.flat: print(element) Output1 2 3 4 5 6 7 8 9 Iterating Over Higher-Dimensional ArraysIteration is similar for arrays with more than two dimensions. In such cases, iteration occurs along the first axis by default. Python import numpy as np # Create a 3D array arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # Iterate over the 3D array for sub_array in arr_3d: print(sub_array) Output[[1 2] [3 4]] [[5 6] [7 8]] Explanation:Each iteration returns a 2D sub-array from the 3D array.Using nditer The numpy.nditer object offers a various way to iterate over arrays. It allows iteration in different orders and provides better control over the iteration process. Python import numpy as np # Using nditer arr = np.array([[1, 2], [3, 4]]) for element in np.nditer(arr): print(element) Output1 2 3 4 We can also specify the order of iteration (row-major order 'C' or column-major order 'F'): Python import numpy as np arr = np.array([[1, 2], [3, 4]]) for element in np.nditer(arr, order='F'): print(element) Output1 3 2 4 Using Enumerate For multidimensional arrays, we can use enumerate to access both the index and value during iteration. Python import numpy as np # Create a 2D array arr = np.array([[10, 20], [30, 40]]) # Enumerate through rows for idx, row in enumerate(arr): print(f"Row {idx}: {row}") OutputRow 0: [10 20] Row 1: [30 40] Using BroadcastingWhen working with arrays of different shapes, Broadcasting allows iteration across combined shapes seamlessly. Python import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([[10], [20]]) # Perform a broadcasted addition for x, y in np.nditer([arr1, arr2]): print(f"{x} + {y} = {x + y}") Output1 + 10 = 11 2 + 10 = 12 3 + 10 = 13 1 + 20 = 21 2 + 20 = 22 3 + 20 = 23 Comment More infoAdvertise with us Next Article Numpy - Iterating Over Arrays T tarunsarawgi_gfg Follow Improve Article Tags : Python Python-numpy Practice Tags : python Similar Reads Numpy Array Indexing Array indexing in NumPy refers to the method of accessing specific elements or subsets of data within an array. This feature allows us to retrieve, modify and manipulate data at specific positions or ranges helps in making it easier to work with large datasets. In this article, weâll see the differe 5 min read Numpy - Array Creation Numpy Arrays are grid-like structures similar to lists in Python but optimized for numerical operations. The most straightforward way to create a NumPy array is by converting a regular Python list into an array using the np.array() function.Let's understand this with the help of an example:Pythonimp 5 min read Basics of NumPy Arrays NumPy stands for Numerical Python and is used for handling large, multi-dimensional arrays and matrices. Unlike Python's built-in lists NumPy arrays provide efficient storage and faster processing for numerical and scientific computations. It offers functions for linear algebra and random number gen 4 min read numpy.array_repr() in Python numpy.array_repr()function is used to convert an array to a string. Syntax : numpy.array_repr(arr, max_line_width=None, precision=None, suppress_small=None) Parameters : arr : [array_like] Input array. max_line_width : [int, optional] The maximum number of columns the string should span. Newline cha 2 min read NumPy Array in Python NumPy (Numerical Python) is a powerful library for numerical computations in Python. It is commonly referred to multidimensional container that holds the same data type. It is the core data structure of the NumPy library and is optimized for numerical and scientific computation in Python. Table of C 2 min read Python Lists VS Numpy Arrays Here, we will understand the difference between Python List and Python Numpy array. What is a Numpy array?NumPy is the fundamental package for scientific computing in Python. Numpy arrays facilitate advanced mathematical and other types of operations on large numbers of data. Typically, such operati 7 min read numpy.array_str() in Python numpy.array_str()function is used to represent the data of an array as a string. The data in the array is returned as a single string. This function is similar to array_repr, the difference being that array_repr also returns information on the kind of array and its data type. Syntax : numpy.array_st 2 min read numpy.asarray() in Python numpy.asarray()function is used when we want to convert input to an array. Input can be lists, lists of tuples, tuples, tuples of tuples, tuples of lists and arrays. Syntax : numpy.asarray(arr, dtype=None, order=None) Parameters : arr : [array_like] Input data, in any form that can be converted to a 2 min read Python - Built-in array vs NumPy array Let us concentrate on the built-in array module first. Built-in array module defines an object type which can efficiently represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects store 5 min read numpy.asfarray() in Python numpy.asfarray()function is used when we want to convert input to a float type array. Input includes scalar, lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Syntax : numpy.asfarray(arr, dtype=type 'numpy.float64') Parameters : arr : [array_like] Input data, in any for 2 min read Like