In this blog post, we’ll be discussing how to find the sum of all elements in an array in Python. We’ll be covering two different methods for doing this, so whether you’re a beginner or more experienced with Python, there should be a method here for you.

Table of Contents

### Using a For Loop

One way to find the sum of all elements in an array is to use a for a loop. With this method, we can iterate through each element in the array and add it to a total sum variable. Let’s take a look at an example:

arr = [1, 2, 3, 4, 5, 6] total_sum = 0 for i in arr: total_sum += i print(total_sum) # Outputs 21

In the code above, we first create an array called **arr**. Next, we create a variable called **total_sum** and set it equal to 0. We do this because we want to start our sum at 0 so that when we add each element in the array, it’s added to the total sum.

Then, we use a for loop to iterate through each element in the array. Finally, we print out the value of **total_sum**, which should be 21 (1 + 2 + 3 + 4 + 5 + 6).

### Using the Built-in Sum Function

If you’re working with Python 3.3 or newer, there’s actually a built-in function that you can use to find the sum of all elements in an array. The syntax looks like this:

arr = [1111, 212, 3333, 44, 5344541, 68913, 10, 100, 20234] total_sum = sum(arr) print(total_sum) # Output: 5438498

As you can see, this code is much simpler than our first method. First off, we don’t need to create a separate variable to keep track of our total sum – we can just set **total_sum** equal to **sum(arr)**. Second, we don’t need to use a for loop because **sum()** will automatically iterate through each element in the array and add it to the total sum.