Home > database >  Why am I getting a change in list elements but not the subtracted value of that element, when using
Why am I getting a change in list elements but not the subtracted value of that element, when using

Time:12-28

I have recently started learning python and am currently on fundamentals so please accept my excuse if this question sounds silly. I am a little confused with the indexing behavior of the list while I was learning the bubble sort algorithm. For example: code

my_list = [8,10,6,2,4]

for i in range(len(my_list)):

print(my_list[i])

for i in range(len(my_list)):

print(i)

Result:

8 10 6 2 4

0 1 2 3 4

The former for loop gave elements of the list (using indexing) while the latter provided its position, which is understandable. But when I'm experimenting with adding (-1) i.e. print (my_list[i-1]) and print(i-1) in both the for loops, I expect -1 to behave like a simple negative number and subtract a value from the indexed element in the first for loop i.e. 8-1=7

Rather, it's acting like a positional indicator of the list of elements and giving the last index value 4.

I was expecting this result from the 2nd loop. Can someone please explain to me why the print(my_list[i-1]) is actually changing the list elements selection but not actually subtracting value 1 from the list elements itself i.e. [8(-1), 10(-1), 6(-1)...

Thank you in advance.

CodePudding user response:

The list index in the expression my_list[i-1] is the part between the brackets, i.e. i-1. So by subtracting in there, you are indeed modifying the index. If instead you want to modify the value in the list, that is, what the index is pointing at, you would use my_list[i] - 1. Now, the subtraction comes after the retrieval of the list value.

CodePudding user response:

Here when you are trying to run the first for loop -

my_list = [8,10,6,2,4]
for i in range(len(my_list)):
    print(my_list[i-1])

Here in the for loop you are subtracting the index not the Integer at that index number. So for doing that do the subtraction like -

for i in range(len(my_list)):
    print(my_list[i]-1)

and you were getting the last index of the list because the loop starts with 0 and you subtracted 1 from it and made it -1 and list[-1] always returns the last index of the list.

Note: Here it is not good practice to iterate a list through for loop like you did above. You can do this by simply by -

for i in my_list:
    print(i-1)

The result will remain the same with some conciseness in the code

  • Related