How to Slice Lists/Arrays and Tuples in Python

>>> word = 'Python'

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)

'Py'

Advanced Python Slicing (Lists, Tuples and Arrays) Increments

There is also an optional second clause that we can add that allows us to set how the list's index will increment between the indexes that we've set.

In the example above, say that we did not want that ugly 3 returned and we only want nice, even numbers in our list. Easy peasy.

>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
 
2
3
>>> a[1:4:2]  # elements from position 1 (included) to 4 (excluded), incremented by 2
[2, 4]

See, it's as simple as that. That last colon tells Python that we'd like to choose our slicing increment. By default, Python sets this increment to 1, but that extra colon at the end of the numbers allows us to specify what we want it to be.

Python Slicing (Lists, Tuples and Arrays) in Reverse

Alright, how about if we wanted our list to be backwards, just for the fun of it? Let's try something crazy.

>>> a[::]             #elements from position 0 , till end, incremented by 1, this is same as the original
[1, 2, 3, 4, 5, 6, 7, 8]
 
>>> a[::-2]
[8, 6, 4, 2]
>>> a[::-1] #elements from position 0 , till end, incremented by -1 (reverse order)
[8, 7, 6, 5, 4, 3, 2, 1]