Michael Howlard
Michael Howlard

Reputation: 247

Looping and appending to a list

def makelist():
    list = []
    initial = [0, 100]
    a = 1
    while a <= 10:
        new_num = (initial[0] + initial[1])//2
        if new_num%2 == 0:
            initial[1] = new_num
        else:
            initial[0] = new_num
        list.append(initial)
        a += 1
    return list

Why does the above code return:

[[43, 44], [43, 44], [43, 44], [43, 44], [43, 44], [43, 44], [43, 44], [43, 44],  [43, 44], [43, 44]]

Rather than:

[[0, 50], [25, 50], [37, 50], [43, 50], [43, 46], [43,44], [43, 44], [43, 44], [43, 44], [43, 44]]

ie. The successive divisions rather than the final division 10 times over.

Thanks

Upvotes: 1

Views: 125

Answers (1)

thefourtheye
thefourtheye

Reputation: 239473

First things first, NEVER name your variables with the builtin types names. In your case list. And your program doesnt work as expected, because

list.append(initial)

you are appending the reference to the same list again and again. At the end, all the elements in the list are pointing to the same list initial. To fix that, you can create a copy of initial like this and append it

list.append(initial[:])

Check this diagram out https://www.lucidchart.com/documents/edit/43c8-0c30-5288c928-a4fe-105f0a00c875. This might help you understand better.

Upvotes: 4

Related Questions