-1

The slice syntax is a handy way to refer to sub-parts of sequences – typically strings and lists. The slice s[start:end] is the elements beginning at start and extending up to but not including end.

E.g

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[2:5])

This will give Output : ['c', 'd', 'e']

But how does extended slicing work.

print(letters[2:4:5])

The above print statement will give ['c'] as output. I can't understand how?

atline
  • 28,355
  • 16
  • 77
  • 113
Nishant Kehar
  • 41
  • 1
  • 7

2 Answers2

1

That is because the 3rd parameter is called "step"

(start:end:step)

When you say:

print(letters[2:4:5])

Basically you are saying, start at index 2, end at 4 and step 5 times.

For example:

print(letters[::2])

Returns ['a', 'c', 'e', 'g']

Two things to note:

1) In your case, even if you said print(letters[2:4:1000]) the output would still be 'c'

2) Default "step" value is 1.

Nicolas Hevia
  • 15,143
  • 4
  • 22
  • 31
  • SO has a duplicate flag to avoid repetitions. It is better to collect all answers under one question then to have them scattered all over the place. – Mr. T Sep 06 '18 at 07:21
0

The slice will essentially work as a step value. Let us assume we have a list of numbers from 1-10. The additional slice will simply work like a "step" value. Here's an example:

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(nums[0:10:2])

We step by 2 each time. Here is our output:

[1, 3, 5, 7, 9]

You get C as your output because You are calling the third index, and then slicing up to the 5th index (index 4 since indexes in Python are zero-based), but you are stepping by a value of 5. So you can't step by 5, because that goes past the index that your slice stops at (index 5, or index 4 in zero-based Python syntax). That is why your code only returns 'c'.

Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27
  • SO has a duplicate flag to avoid repetitions. It is better to collect all answers under one question then to have them scattered all over the place. – Mr. T Sep 06 '18 at 07:22