简体   繁体   中英

Adding 1 to last value of a list

I am trying to add 1 to the last value in a list . list[-1] should give me the last value. Code below:

def plusOne( l):
    for idx, item in enumerate(l):
      l[-1]=l[-1]+1
    return l

print(plusOne(v))

Problem: Upon running the code the answer I get it v=[4,3,2,5] when I was expecting v=[4,3,2,2] . This works when I use [1,2,3] to test. When I put a breakpoint on l[-1] line I see:

idx 0 item 4
idx 1 item 3
idx 1 item 3
idx 2 item 2
idx 3 item 4

Can someone kindly explain why it works for [1,2,3] and not [4,3,2,1] ?

[1, 2, 3] doesn't work for me; it returns [1, 2, 6] .

You shouldn't need any kind of loop here. The reason it is adding 1 multiple times is because you put the code that increments the last element in a loop. Thus, when the list has say, 4 elements, the last element is incremented 4 times.

Try this instead (you can also use ... += 1 instead of ... = ... + 1 ):

def plusOne(l):
    l[-1] += 1
    return l

Note that this modifies the original list. Basically, execution of this function will modify the list passed into it (in your case, v ). To make a copy:

def plusOne(l):
    l = l[:]
    l[-1] += 1
    return l

You can do this:

def plusOne(l):
    l[-1] += 1
    return l

The reason why yours does not work is because you are essentially going through each element and for every element there is, the last element is incremented by one. Thus, if there are 3 elements, the final element will be incremented by 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM