Search code examples
pythonlistsplice

Python splicing list does not include first element when working backwards


new_list = [i + 1 for i in range(16)]

sec_list = new_list[(len(new_list) - 2):0:-2]

print(new_list)

print(sec_list)

Actual Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

[15, 13, 11, 9, 7, 5, 3]

Desired output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

[15, 13, 11, 9, 7, 5, 3, 1] <---- I want the 1 to be present

Just want to clarify how this works. I thought [start: end: increment/decrement]


Solution

  • This is what you need

    sec_list = new_list[(len(new_list) - 2)::-2]
    print(sec_list) # [15, 13, 11, 9, 7, 5, 3, 1]
    

    You made a mistake in second argument:

    new_list[(len(new_list) - 2):0:-2]
    

    start: (len(new_list) - 2) stop: 0 step: -2

    which means that you stopped on 0 item that's why 1 was not included

    also you can read about this there