
Python Data Analyst Interview: Common Slicing Operations You Must 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
