Home > database >  why is the count backwards
why is the count backwards

Time:09-19

I have the following code but I can not understand why the result shows a count going backwards if no -1 is used

def strange(n):
    list = []

    for i in range(0, n):
        list.insert(0, i)

    return list


print(strange(15))

CodePudding user response:

You fetch each value in the list in order, but when you insert data, it is always inserted to 0 (beginning on the left side of the list)

CodePudding user response:

It appears backwards because of this line of code:

list.insert(0, i)

Every time you insert a value, it is saved to index 0, so the resulting list goes backward.

If you you use the append method instead, it will be in ascending order. You can also replace the 0 in insert with some other number, which will put the value at that position, if the index exists.

CodePudding user response:

Because insert inserts before index

arr = [1,2,3]
arr.insert(0, 0)
print(arr) # -> [0,1,2,3]

Use .append(i) instead, it will add obj at the end of the list

Or you can use _list.insert(i, i) which will append obj to the end too

def strange(n): 
    _list = []
    for i in range(0, n):
        _list.append(i)

    return _list

print(strange(15))
And also, don't call your variable as a built-in type list, it's bad practice, because you can't access it anymore, it will be rewritten with your new value.
  • Related