-1
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]

instinct246
  • 960
  • 9
  • 15
Codegenesis G
  • 79
  • 1
  • 1
  • 9

1 Answers1

1

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

alex2007v
  • 1,230
  • 8
  • 12
  • Because that's how ranges work: they include the start, but not the end. `range(16)` (equivalently, `range(0, 16, 1)`) is from 0 to 15. In the same way, `range(16, 0, -1)` is from 16 to 1. Note also that you can replace `len(new_list) - 2` with just `-2`. You can compact everything like this: `new_list = list(range(1, 17)); sec_list = new_list[-2::-2]` – Amadan Jan 28 '20 at 04:17