[python] Iterating over arrays in Python 3

I haven't been coding for awhile and trying to get back into Python. I'm trying to write a simple program that sums an array by adding each array element value to a sum. This is what I have:

def sumAnArray(ar):
    theSum = 0
    for i in ar:
        theSum = theSum + ar[i]
    print(theSum)
    return theSum

I get the following error:

line 13, theSum = theSum + ar[i]
IndexError: list index out of range

I found that what I'm trying to do is apparently as simple as this:

sum(ar)

But clearly I'm not iterating through the array properly anyway, and I figure it's something I will need to learn properly for other purposes. Thanks!

This question is related to python arrays python-3.x sum

The answer is


When you loop in an array like you did, your for variable(in this example i) is current element of your array.

For example if your ar is [1,5,10], the i value in each iteration is 1, 5, and 10. And because your array length is 3, the maximum index you can use is 2. so when i = 5 you get IndexError. You should change your code into something like this:

for i in ar:
    theSum = theSum + i

Or if you want to use indexes, you should create a range from 0 ro array length - 1.

for i in range(len(ar)):
    theSum = theSum + ar[i]

The for loop iterates over the elements of the array, not its indexes. Suppose you have a list ar = [2, 4, 6]:

When you iterate over it with for i in ar: the values of i will be 2, 4 and 6. So, when you try to access ar[i] for the first value, it might work (as the last position of the list is 2, a[2] equals 6), but not for the latter values, as a[4] does not exist.

If you intend to use indexes anyhow, try using for index, value in enumerate(ar):, then theSum = theSum + ar[index] should work just fine.


While iterating over a list or array with this method:

ar = [10, 11, 12]
for i in ar:
    theSum = theSum + ar[i]

You are actually getting the values of list or array sequentially in i variable. If you print the variable i inside the for loop. You will get following output:

10
11
12

However, in your code you are confusing i variable with index value of array. Therefore, while doing ar[i] will mean ar[10] for the first iteration. Which is of course index out of range throwing IndexError

Edit You can read this for better understanding of different methods of iterating over array or list in Python


You can use

    nditer

Here I calculated no. of positive and negative coefficients in a logistic regression:

b=sentiment_model.coef_
pos_coef=0
neg_coef=0
for i in np.nditer(b):
    if i>0:
    pos_coef=pos_coef+1
    else:
    neg_coef=neg_coef+1
print("no. of positive coefficients is : {}".format(pos_coef))
print("no. of negative coefficients is : {}".format(neg_coef))

Output:

no. of positive coefficients is : 85035
no. of negative coefficients is : 36199

Questions with python tag:

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Upgrade to python 3.8 using conda Unable to allocate array with shape and data type How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip How to prevent Google Colab from disconnecting? "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function? "E: Unable to locate package python-pip" on Ubuntu 18.04 Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session' Jupyter Notebook not saving: '_xsrf' argument missing from post How to Install pip for python 3.7 on Ubuntu 18? Python: 'ModuleNotFoundError' when trying to import module from imported package OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website How to setup virtual environment for Python in VS Code? Pylint "unresolved import" error in Visual Studio Code Pandas Merging 101 Numpy, multiply array with scalar What is the meaning of "Failed building wheel for X" in pip install? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed Could not install packages due to an EnvironmentError: [Errno 13] OpenCV !_src.empty() in function 'cvtColor' error ConvergenceWarning: Liblinear failed to converge, increase the number of iterations How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How do I install opencv using pip? How do I install Python packages in Google's Colab? How do I use TensorFlow GPU? How to upgrade Python version to 3.7? How to resolve TypeError: can only concatenate str (not "int") to str How can I install a previous version of Python 3 in macOS using homebrew? Flask at first run: Do not use the development server in a production environment TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array What is the difference between Jupyter Notebook and JupyterLab? Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this? Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'" How do I resolve a TesseractNotFoundError? Trying to merge 2 dataframes but get ValueError Authentication plugin 'caching_sha2_password' is not supported Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

Questions with arrays tag:

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array? How to update an "array of objects" with Firestore? How to increment a letter N times per iteration and store in an array? Cloning an array in Javascript/Typescript use Lodash to sort array of object by value TypeScript enum to object array How do I check whether an array contains a string in TypeScript? How to use forEach in vueJs? Program to find largest and second largest number in array How to plot an array in python? How to add and remove item from array in components in Vue 2 console.log(result) returns [object Object]. How do I get result.name? How to map an array of objects in React How to define Typescript Map of key value pair. where key is a number and value is an array of objects Removing object from array in Swift 3 How to group an array of objects by key Find object by its property in array of objects with AngularJS way Getting an object array from an Angular service push object into array How to get first and last element in an array in java? Add key value pair to all objects in array How to convert array into comma separated string in javascript Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0) Angular 2 declaring an array of objects How can I loop through enum values for display in radio buttons? How to convert JSON object to an Typescript array? Angular get object from array by Id Add property to an array of objects Declare an array in TypeScript ValueError: all the input arrays must have same number of dimensions How to convert an Object {} to an Array [] of key-value pairs in JavaScript Check if a value is in an array or not with Excel VBA TypeScript add Object to array with push Filter array to have unique values remove first element from array and return the array minus the first element merge two object arrays with Angular 2 and TypeScript? Creating an Array from a Range in VBA "error: assignment to expression with array type error" when I assign a struct field (C) How do I filter an array with TypeScript in Angular 2? How to generate range of numbers from 0 to n in ES2015 only? TypeError: Invalid dimensions for image data when plotting array with imshow()

Questions with python-3.x tag:

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7? TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array How do I resolve a TesseractNotFoundError? Could not find a version that satisfies the requirement tensorflow Not able to pip install pickle in python 3.6 json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) installing urllib in Python3.6 pip install returning invalid syntax Unable to import path from django.urls Display all dataframe columns in a Jupyter Python Notebook How to make Firefox headless programmatically in Selenium with Python? How to import cv2 in python3? Pipenv: Command Not Found Error in Python script "Expected 2D array, got 1D array instead:"? Fixed digits after decimal with f-strings How do I upgrade the Python installation in Windows 10? Pip error: Microsoft Visual C++ 14.0 is required Python error message io.UnsupportedOperation: not readable Anaconda Installed but Cannot Launch Navigator Conda command is not recognized on Windows 10 TypeError: can't pickle _thread.lock objects How do you fix the "element not interactable" exception? How to print a specific row of a pandas DataFrame? Relative imports - ModuleNotFoundError: No module named x SyntaxError: unexpected EOF while parsing ImportError: No module named 'django.core.urlresolvers' Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'? What is the purpose of "pip install --user ..."? Add Legend to Seaborn point plot How to install pip for Python 3.6 on Ubuntu 16.10? Python sockets error TypeError: a bytes-like object is required, not 'str' with send function WinError 2 The system cannot find the file specified (Python) Python 3.6 install win32api? error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Python 3 - ValueError: not enough values to unpack (expected 3, got 2) matplotlib: plot multiple columns of pandas data frame on the bar chart Unable to set default python version to python3 in ubuntu TypeError: '<=' not supported between instances of 'str' and 'int' pandas: merge (join) two data frames on multiple columns Replacing a character from a certain index Scrolling to element using webdriver?

Questions with sum tag:

Iterating over arrays in Python 3 Get total of Pandas column Pandas: sum DataFrame rows for given columns How to find sum of several integers input by user using do/while, While statement or For statement SQL Sum Multiple rows into one Python Pandas counting and summing specific conditions SELECT query with CASE condition and SUM() Using SUMIFS with multiple AND OR conditions How to SUM parts of a column which have same text value in different column in the same row how to count the total number of lines in a text file using python Python sum() function with list parameter Java method to sum any number of ints Sum all the elements java arraylist Sum values from an array of key-value pairs in JavaScript How to find the cumulative sum of numbers in a list? Sum the digits of a number Add SUM of values of two LISTS into new LIST How get total sum from input box values using Javascript? SUM of grouped COUNT in SQL Query Sum function in VBA Finding moving average from data points in Python Summing elements in a list Why does the 'int' object is not callable error occur when using the sum() function? How can I use SUM() OVER() How to sum data.frame column values? MYSQL Sum Query with IF Condition How do I get SUM function in MySQL to return '0' if no values are found? Sum of Numbers C++ Sum one number to every element in a list (or array) in Python How to sum all the values in a dictionary? MySql sum elements of a column How do you find the sum of all the numbers in an array in Java? Sum a list of numbers in Python C# List of objects, how do I get the sum of a property Calculating the SUM of (Quantity*Price) from 2 different tables Using GroupBy, Count and Sum in LINQ Lambda Expressions SQL Update to the SUM of its joined values SQL not a single-group group function What are the ways to sum matrix elements in MATLAB? How to sum array of numbers in Ruby? How to sum all column values in multi-dimensional array? How can I change NULL to 0 when getting a single value from a SQL function? Performing a query on a result from another query?