You do it if there is something in your loop that will use an index rather than the elements of the array. For instance, sometimes you want to sample something from another array that is not your loop array A cleaner way to do it is by using enumerate function for i, item in enumerate(array): The index gets assigned to i and whatever element of the array gets assigned to item. This may also be a bad habit from Matlab, people that come from Matlab are more used to looping over indexes. Answer from waspbr on reddit.com
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_array_loop.asp
Python Loop Through an Array
Python Examples Python Compiler ... Bootcamp Python Certificate Python Training ... You can use the for in loop to loop through all the elements of an array....
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ numpy โ€บ numpy_array_iterating.asp
NumPy Array Iterating
Iterating means going through elements one by one. As we deal with multi-dimensional arrays in numpy, we can do this using basic for loop of python.
Discussions

python - Iterating through a for loop with the size of an array - Stack Overflow
I want my program to be able to print out the sum of all numbers below n that are divisible by 3 and also 5. #!/bin/python3 import sys import math arr = [] arr3 = [] arr5 = [] tn = 1 sum1 = 0 sum... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Loop over an an array of array
I have an array of arrays I want to loop over to return two arrays called hills and valleys. When looping through each element, we check the item at index 1 that is element[0] if the value is equal to zero, we create another array and push the value inside. we keep a trace of it still when ... More on discuss.python.org
๐ŸŒ discuss.python.org
0
0
November 28, 2023
python - loop through array or list in variable steps - Stack Overflow
I'm trying to figure out how to loop through an array or list in variable steps. So for example, if I have the following list... ... However, I'm not quite clear how I can implement this logic as it seems like I can't change my index value I iterate through. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to iterate through all documents? (Firestore)

assuming that you want to use javascript and firestore (cause u said web and firestore is my favorite), after you set all your information to instantiate your firebase account, it would look like this:

const yourData = await   
admin.firestore().collection(THE_COLLECTION_YOU\_WANT_TO_QUERY).get().then((doc) => {
   const temp = \[\]
   const response = data.forEach((doc) => {
     temp.push(doc.data())
  })
  return temp
})

// so here the yourData is iterable... here comes the part you just mentioned
for (let doc of yourData) {
   console.log(doc) // each element is here!
}

I hope this can help u started :)!

Good luck!

More on reddit.com
๐ŸŒ r/Firebase
2
2
August 7, 2017
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ numpy โ€บ numpy_iterating_over_array.htm
NumPy - Iterating Over Array
The nditer() function in NumPy provides an efficient multidimensional iterator object that can be used to iterate over elements of arrays. It uses Python's standard iterator interface to visit each element of an array.
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python iterate over an array
Python Iterate Over an Array - Spark By {Examples}
May 31, 2024 - How to use for loop to iterate over an array in Python? Iterate over an array is also referred to as looping through all the elements of an array which can easily perform by using for loops with syntax for x in arrayObj:.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.4 Manual
The most basic task that can be done with the nditer is to visit every element of an array. Each element is provided one by one using the standard Python iterator interface.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ for-loops-in-python
For Loops in Python
February 1, 2020 - The range function now does what xrange does in Python 2.x ยท A = ["hello", 1, 65, "thank you", [2, 3]] for value in A: print(value) ... fruits_to_colors = {"apple": "#ff0000", "lemon": "#ffff00", "orange": "#ffa500"} for key in fruits_to_colors: print(key, fruits_to_colors[key]) ... If you absolutely need to access the current index of your iteration, do NOT use range(len(iterable))!
Find elsewhere
Top answer
1 of 4
3

Your solution seems correct - but it seems u have a couple of syntax errors if you're using python You also have to re-initialize sum1 & sum2 between test cases. Right now you get the total sum of all arrs rather than arr[x]-hopefully that makes sense. You also have to remove duplicate numbers from the sum. For instance, if you're getting the sum of all numbers up to 20 - you'll end up adding 15 twice as it is divisible by 3 and 5. So the inner for loops will add it twice to the sum. So you'll need to remove 15 to get rid of duplicates.

for x in range(len(arr)): #by default range starts at o. therefore, range(len(arr)) = range(0, len(arr)) 
    sum1 = 0 # you forgot to initialize sum1
    sum2 = 0 # you forgot to initialize sum2
    duplicates = 0 #you have to remove duplicates from the answer
    for b5 in range (0, arr[x], 5): #you have to add the colons here
        sum1 = sum1 + b5
    for b3 in range (0, arr[x], 3): #you have to add the colons here
        sum2 = sum2 + b3
    for dup in range(0, arr[x], 3*5): # removes duplicates from the final sum
        duplicates = duplicates + dup
    sum = sum1 + sum2 - duplicates 
    print(sum)

This is an O(n^2) solution - you can drop it down to O(n) using a little bit of math.

You'll notice that the inner for loops can be represented using the formula sum(n)=ฮฃd*i=d*ฮฃi-where the summation starts at i = 0, end at โŒŠ(n-1)/dโŒ‹ and d is the divisor (in the case of your question d=3 or 5).

for b5 in range (0, arr[x], 5):
    sum1 = sum1 + b5

(https://en.wikipedia.org/wiki/Summation)

There is a very common summation formula that is commonly used to convert summations into a closed-form expression (something with finite steps - which is O(1))

ฮฃi=n*(n+1)/2

In the case of the inner loop - it would be sum(n) = d*(โŒŠ(n-1)/dโŒ‹)*(โŒŠ(n-1)/dโŒ‹+1)/2.

let,

f(n,d) = (โŒŠ(n-1)/dโŒ‹+1)/2

Therefore, the solution to your problem would be f(n,3)+f(n,5)-f(n,3*5)

Which would convert the inner for loops from O(n) to O(1). Which, means your entire solution would be O(n).

I'll let you figure out the code on your own. However, theoretically, there is a better solution; such that as arr grows indefinitely the work scales linearly rather than quadratically.

2 of 4
0
  1. Create Array with input number (Eg. arr = [12, 15, 4] )
  2. Iterate over the created Array
  3. In for loop check if number are divisible by 3 and 5

Sample code:

    arr = [12, 15, 4]
    total = 0
    
    for num in arr:
        if num % 3 == 0 and num % 5 == 0:
            total = total + num
    
    print(total) # 15
๐ŸŒ
CodeSignal
codesignal.com โ€บ learn โ€บ courses โ€บ applying-simple-looping-in-practice-with-python โ€บ lessons โ€บ iterating-through-an-array-from-middle-to-ends
Iterating Through an Array from Middle to Ends
For this, we can effectively utilize ... end of the list. In each iteration, we add the element at index left to the new_order list, decrease the left pointer by one, add the element at index right, and increase the right pointer by one....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ iterate-over-a-list-in-python
Iterate over a list in Python - GeeksforGeeks
List comprehension is similar to for loop. It provides the shortest syntax for looping through list. ... a = [1, 3, 5, 7, 9] # On each iteration val is passed to print function # And printed in the console.
Published ย  December 27, 2025
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Loop over an an array of array - Python Help - Discussions on Python.org
November 28, 2023 - When looping through each element, we check the item at index 1 that is element[0] if the value is equal to zero, we create another array and push the value inside. we keep a trace of it still when ...
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_loop_arrays.htm
Python - Loop Arrays
import array as arr newArray = arr.array('i', [56, 42, 23, 85, 45]) for iterate in newArray: print (iterate)
๐ŸŒ
NumPy
numpy.org โ€บ devdocs โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.5.dev0 Manual
The most basic task that can be done with the nditer is to visit every element of an array. Each element is provided one by one using the standard Python iterator interface.
๐ŸŒ
Pluralsight
pluralsight.com โ€บ tech insights & how-to guides โ€บ tech guides & tutorials
Iterating Numpy Arrays | Pluralsight
November 12, 2018 - If you do not want to write two ... a one-dimensional array. For example: ... NumPy provides a multi-dimensional iterator object called nditer to iterate the elements of an array....
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.1 โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.1 Manual
The most basic task that can be done with the nditer is to visit every element of an array. Each element is provided one by one using the standard Python iterator interface.
๐ŸŒ
Trey Hunner
treyhunner.com โ€บ 2016 โ€บ 04 โ€บ how-to-loop-with-indexes-in-python
How to loop with indexes in Python
Pythonโ€™s built-in enumerate function ... each item in the list: The enumerate function gives us an iterable where each element is a tuple that contains the index of the item and the original item value....
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ 5 best ways to iterate over an array in python
5 Best Ways to Iterate Over an Array in Python - Be on the Right Side of Change
February 26, 2024 - This article explores five common techniques to achieve this, catering to various scenarios and Pythonic idioms. The for loop is the most common and straightforward method for iterating through an array in Python.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-program-to-iterate-over-an-array
Python Program to Iterate Over an Array
May 15, 2023 - This is the easiest method to iterate an array in python programming. Here the for loop iterates all the array elements. In this example, The variable ele is the loop variable it stores the element corresponding to the each iteration. Rather than using the index number to accasses one by one element, here we can simply loop through and disply the array elements in the output.
Top answer
1 of 3
3

Don't use a for loop.

for loops in python are different than in C or Java. In those languages, a for loop has an initial condition, a termination condition, and an increment for each time the loop runs. Whereas in python, a for loop is more of a for each loop - you give it an iterable object, and it runs the code for every item in that iterable object.

Modifying the iterable object while you're running through it is a bad idea that can have difficult-to-predict repercussions and will usually break your code.


However, you can always use a while loop:

a = [0,0,1,0,0,1,0]
idx = 0

while(idx < len(a) - 2):
    print(idx)
    if a[idx + 2] == 0:
        idx += 2
    elif a[idx + 2] == 1:
        idx += 1
print(idx)

which produces the expected output

0 1 3 4 6

Or, if you change the increments to 3 and 2 respectively, rather than 2 and 1,

0 2 5
2 of 3
0

Your reasoning is pretty confusing, and I don't see ANY application for this, but here is how I understand your problem...

The reason is because you aren't actually returning the values, you're simply returning the index + 3, which is wrong to begin with. What you're trying to do is point to a new index of the array based on its value and return the index if it contains a value greater than 0.

You need to reference the index you want, check its value, then return the index which contains a value.

a = [0, 0, 1, 0, 0, 1, 0]
for i, v in enumerate(a):
   if i == 0:
      print(i)
      next
   if v == 0:
      next
   else
      print(i)

But let's be honest, this is extremely ugly and un-pythonic. Let's simply check for whether a[i] contains a value, and if so, return the index...

for i, v in enumerate(a):
   if v or i == 0:
      print(i)

The purpose of if v or i == 0 is to check if v has a value, if so, print the index. OR if we are looking at the first element of i.

If you want to EXPLICITLY move the index by two, you must set your index at the start and use a while loop, since enumerate can't help you here and doesn't actually let you move the indicies...

a = [0, 0, 1, 0, 0, 1, 0]
i = 0
while i < len(a) - 1:   # -1 to avoid out of bounds error
   print(i)
   if a[i + 2] == 0:
      i += 2
   elif a[i + 2] == 1:
      i += 1
print(i)            # Final print statement for the last index at the end of the while loop

I want to impress upon you the fact that this solution does NOT scale with different or larger lists, which is why it isn't recommended. By simply checking for whether a value does or doesn't exist, you guarantee your accuracy.

You should simply return the index based upon whether or not it contains a value. Even for very large lists, this will be extremely fast, and will always scale, even for values greater than 1.

The only other reason I would see you would want to do this differently is if you're doing string-search algorithms.

๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ numpy โ€บ numpy iterating over array
NumPy Iterating Over Array - Scaler Topics - Scaler Topics
September 9, 2022 - While forcing an iteration order, we noticed that the external loop option might break the elements of an array into smaller chunks because, with constant steps, the elements cannot be visited in the proper order. When developing C code, this is fine. However, in pure Python programming, it ...