0

I saw the following code in a coding challenge, I don't know why it returns 3, but check the code and tell me what do u think.

myList = [1,2,3,4]
for i in myList:
   i += 1
print(myList[-2])

When I saw the code I said it will print 4 because in the loop we added 1 in all integers in the list, and [-2] is supposed to give me the second-last value, which is 4 according to what I think.

I know I'm missing something here but I don't know what it is, so if anyone could explain this to me I'll appreciate it. Probably I'm not understanding i, I'm not sure.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Maain
  • 27
  • 3

4 Answers4

2

Explanation

The line:

for i in myList

Iterates over the items of the list myList, not it's indices.

The line in it that adds one i += 1 doesn't assign the new value to the list, therefore is unchanged.

How to Fix

However, if we change the code to iterate over the indices:

for i in range(len(myList))

We can now change the values in the list:

myList[i] += 1

Code fix:

myList = [1,2,3,4]
for i in range(len(myList)):
   myList[i] += 1

# 4
print(myList[-2])

Some Advice

It's a convenience in Python to name variables with lower-case, underscore separated names.

So myList would be my_list.

It doesn't change how the program behaves but would be more readable for your future teammates.

Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
0

Your reasoning is ok, but note that the changed value is not stored back to the list replacing the original (the list remains unchanged!)

89f3a1c
  • 1,430
  • 1
  • 14
  • 24
0

The index of list is

    myList = [1, 2, 3, 4]
 +ve index    0  1  2  3
 -ve index   -4 -3 -2 -1

i is modified in that iteration and is not stored in list. Hence myList[-2] is 3

Ajay A
  • 1,030
  • 1
  • 7
  • 19
-1

i is the current item of your list, i took the value but not is a reference, therefore is unchanged

Reinier Hernández
  • 428
  • 1
  • 6
  • 22