Appending elements while looping using append() is correct and it's a built-in method within Python lists.

However you can have the same result:

Using list comprehension:

result_t = [k for k in range(1,6)]
print(result_t)
>>> [1, 2, 3, 4, 5]

Using + operator:

result_t = []
for k in range(1,6):
    result_t += [k]

print(result_t)
>>> [1, 2, 3, 4, 5]

Using special method __iadd__:

result_t = []
for k in range(1,6):
    result_t.__iadd__([k])

print(result_t)
>>> [1, 2, 3, 4, 5]
Answer from Chiheb Nexus on Stack Overflow
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_loop_arrays.htm
Python - Loop Arrays
import array as arr # creating array a = arr.array('i', [96, 26, 56, 76, 46]) # checking the length l = len(a) # loop variable idx = 0 # while loop while idx < l: print (a[idx]) # incrementing the while loop idx+=1 ยท On executing the above code, it will display the following output โˆ’ ... We can find the length of array with built-in len() function. Use it to create a range object to get the series of indices and then access the array elements in a for loop...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_array_loop.asp
Python Loop Through an Array
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... You can use the for in loop to loop through all the elements of an array.
People also ask

How does a 'for loop' work in Python?
A 'for loop' in Python iterates over a sequence (like a list, tuple, or string) or any iterable object, executing a block of code for each element. The loop assigns each item from the sequence to a loop variable in each iteration until all items are processed.
๐ŸŒ
studysmarter.co.uk
studysmarter.co.uk โ€บ for loop in python
for Loop in Python: Syntax & Range | StudySmarter
Can a 'for loop' in Python be nested within another 'for loop'?
Yes, a 'for loop' in Python can be nested within another 'for loop'. This allows iterating over multiple sequences or creating multi-dimensional iterations, such as traversing through a matrix or a list of lists.
๐ŸŒ
studysmarter.co.uk
studysmarter.co.uk โ€บ for loop in python
for Loop in Python: Syntax & Range | StudySmarter
How can I iterate over a list using a 'for loop' in Python?
You can iterate over a list in Python using a 'for loop' by writing `for item in list:`, where `item` represents each element in the list. This loop will execute a block of code for each element.
๐ŸŒ
studysmarter.co.uk
studysmarter.co.uk โ€บ for loop in python
for Loop in Python: Syntax & Range | StudySmarter
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.4 Manual
For the nditer object, this means letting the iterator take care of broadcasting, dtype conversion, and buffering, while giving the inner loop to Cython. For our example, weโ€™ll create a sum of squares function. To start, letโ€™s implement this function in straightforward Python.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ numpy โ€บ numpy_array_iterating.asp
NumPy Array Iterating
As we deal with multi-dimensional arrays in numpy, we can do this using basic for loop of python.
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python iterate over an array
Python Iterate Over an Array - Spark By {Examples}
May 31, 2024 - For example, # Iterate by getting index and value for index, value in np.ndenumerate(arr): print(index, value) Yields below output. ... If you have a multi-dimensional array you need to perform multiple loops, to overcome this problem use nditer function of the NumPy module in Python.
๐ŸŒ
StudySmarter
studysmarter.co.uk โ€บ for loop in python
for Loop in Python: Syntax & Range | StudySmarter
... Use nested for loops to access and manipulate the individual elements within the array, or use the numpy.nditer() method if working with the numpy library. For example: 1) for row in example_array: for item in row: print(item) 2) for item in np.nditer(example_array): print(item)
Find elsewhere
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Loop over an an array of array - Python Help - Discussions on Python.org
November 28, 2023 - 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 ...
๐ŸŒ
Dataquest
dataquest.io โ€บ blog โ€บ tutorial-advanced-for-loops-python-pandas
Tutorial: Advanced Python for Loops โ€“ Dataquest
March 11, 2025 - Now, let's take a look at how for loops can be used with common Python data science packages and their data types. We'll start by looking at how to use for loops with numpy arrays, so let's start by creating some arrays of random numbers.
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
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ for-loops-in-python
For Loops in Python
February 1, 2020 - If you absolutely need to access the current index of your iteration, do NOT use range(len(iterable))! This is an extremely bad practice and will get you plenty of chuckles from senior Python developers. Use the built in function enumerate() instead: for index, item in enumerate(shopping_basket): print("Item", index, "is a", item) Pyhton permits you to use else with for loops, the else case is executed when none of the conditions with in the loop body was satisfied.
๐ŸŒ
DataCamp
campus.datacamp.com โ€บ courses โ€บ intermediate-python โ€บ loops
Loop over NumPy array | Python
Two NumPy arrays that you might ... the numpy package under the local alias np. Write a for loop that iterates over all elements in np_height and prints out "x inches" for each element, where x is the value in the array....
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.1 โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.1 Manual
For the nditer object, this means letting the iterator take care of broadcasting, dtype conversion, and buffering, while giving the inner loop to Cython. For our example, weโ€™ll create a sum of squares function. To start, letโ€™s implement this function in straightforward Python.
๐ŸŒ
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu โ€บ notebooks โ€บ chapter05.01-For-Loops.html
For-Loops โ€” Python Numerical Methods
A less intrusive command is the keyword continue, which skips the remaining code in the current iteration of the for-loop, and continues on to the next element of the looping array. See the following example, that we use the keyword continue to skip the print function to print 2:
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-program-to-iterate-over-an-array
Python Program to Iterate Over an Array
lst = ['P', 'y', 't', 'h', 'o', ... the iterations repeatedly until a given condition is satisfied. In this example, the condition I < len(lest) is executed to iterate the all array elements....
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 1684765 โ€บ python-array-for-loop
Python array for loop | Sololearn: Learn to code for FREE!
Came across this for loop in a python challenge. I'm still trying to understand exactly what it's doing. Any help? arr = [(5,8,0), (2,4)] sum = [] for x, *y in arr:
๐ŸŒ
LearnPython.com
learnpython.com โ€บ blog โ€บ python-list-loop
7 Ways to Loop Through a List in Python | LearnPython.com
Although weโ€™ve used for num in ... in this example, itโ€™s usually better to use for num in np.nditer(nums): when youโ€™re working with large lists. The np.nditer function returns an iterator that can traverse the NumPy array, which is computationally more efficient than using a simple for loop. Python loops are ...
๐ŸŒ
Studytonight
studytonight.com โ€บ python โ€บ looping-in-python
Python Loops - for Loop and while Loop | Studytonight
In this section, we will see how loops work in python. Looping is simply a functionality that is commonly used in programming for achieving repetitive tasks. It can vary from iterating each element of an array or strings, to modifying a whole database.