Home > database >  Iteration in a function
Iteration in a function

Time:09-28

I would like to calculate the average for a given list of number and then iterate it once into the original list so the result of the average is the same if without any iteration.

def avg_lists1(a):
  for i in list(a):
    a.append(i)
    print("a is", a)
    a = [i   i]
    return sum(a)/len(a)


print(avg_lists1([1, 2, 4]))

The result is

a is [1, 2, 4, 1]

2.0

The append in (line 3) or/and the add the element of the list of number (in line 5) is not able to do the iteration to include the number into the list again.

What can I enable the iteration?

CodePudding user response:

Although your question is very unclear about what you want to do. I think what you are trying to achieve is to iterate through a list, put it into another list, and then calculate average. This is how you can do it.

def avg_lists1(a):
    b = []
    for i in list(a):
        b.append(i)
    return sum(b)/len(b)


print(avg_lists1([1, 2, 4]))

It is never a good idea to modify an iterable during iteration. You can actually avoid the whole for loop and append the list to another list in one go like the following.

b.extend(a)

As I said earlier, it is not very clear what you want to achieve.

CodePudding user response:

I am not clear with your ask. What I can see is that the size of the list changes and so does the iteration. It's better to start with a generator which keeps an index of your list. Also you are changing the original intent of variable a which is to keep a track of your original list.

Also once you return the output from a function while in loop your iterations are incomplete. Hence try to avoid that too.

import copy

def avg_lists1(a):
  b = copy.copy(a)
  for idx in range(len(b)):
    b.append(b[idx])
  print("New List:",b)
  return sum(a)/len(a), sum(b)/len(b)

CodePudding user response:

Your question is not clear and what you want, what I got is: You want to append all the elements which are in list to the same list and make sure the average does not change. Have posted the code with this understanding.

def avg_lists1(a):
    avg_bef = sum(a)/len(a)
    for i in list(a):
        a.append(i)
    
    print("a is", a)
    avg_after = sum(a)/len(a)
    return avg_bef, avg_after


print(avg_lists1([1, 2, 4, 1]))

Output:

a is [1, 2, 4, 1, 1, 2, 4, 1]
(2.0, 2.0)
  • Related