
Python Slicing Techniques Every Data Analyst Should Know
Slicing operations are very common and often come up in interview problems.
Here are practical and fun examples of slicing using different step values:
π Basic Reversal
s = "hello"
s[::-1] # "olleh"
nums = [1, 2, 3, 4, 5]
nums[::-1] # [5, 4, 3, 2, 1]
π’ Reverse every second character
Starts from the end (g), skips one each time going backward.
s = "abcdefg"
s[::-2] # "geca"
π Remove first and last characters, then reverse
-
s[1:-1]→ removes'O'and'I'→'penA' -
[:: -1]→'Anep'
s = "OpenAI"
s[1:-1][::-1] # "enp"
π Get every 2nd element (forwards)
nums = [0, 1, 2, 3, 4, 5, 6]
nums[::2] # [0, 2, 4, 6]
βοΈ Slice part and reverse
s = "datascience"
s[1:6][::-1] # "satas"
π Reverse only a portion
s = "abcdefgh"
s[:5][::-1] # "edcba"
-
Slice first 5 chars →
"abcde" -
Reverse it →
"edcba"
π§ͺ String palindrome check (shortcut)
def is_palindrome(word):
return word == word[::-1]
is_palindrome("madam") # True
is_palindrome("hello") # False
