0

I want to loop over list with indexes, while looping I want for loop to consider both start index and last index, although it respect start index it does not respect last index. The code I am trying is this:

arr = [0,1,2,3,4,5,6,7,8,9]

for i in arr[4:8]:
        print(i)

Actual Result:

4
5
6
7

Desired Result:

4
5
6
7
8
D555
  • 1,704
  • 6
  • 26
  • 48
  • `4:8` are four items. Why do you expect it to be five items? – Tomalak May 10 '20 at 06:19
  • 1
    This is how slices are defined in Python (for objects of the standard library). You have to add one to the end index. – Michael Butscher May 10 '20 at 06:19
  • 1
    The end index is not inclusive in list slices. – Barmar May 10 '20 at 06:19
  • I could ask the other way around - why are you surprised that the end of the slice is at `7`, but not surprised that the start of the slice is at `4`? A slice `0:4` *must* stop at `3`, so that a slice `4:8` can start at `4` - otherwise the whole system does not make any sense – Tomalak May 10 '20 at 06:30

2 Answers2

1

You need to have a "strategic" + 1 because slicing in Python excludes the last element:

for i in arr[4:8 + 1]:
    print(i)
norok2
  • 25,683
  • 4
  • 73
  • 99
1

In python slicing end index is not inclusive.

For example

print(list(range(4,8))
#[4, 5, 6, 7]
#won't include 8

Most of the cases this is sufficient.

For for specific use case, you may need to add '1' to the index.

for i in arr[start_index:end_index+1]:
    print(i)
Wickkiey
  • 4,446
  • 2
  • 39
  • 46