SLICE WITH STEP PARAMETER
Python
#!/usr/bin/env python3
"""
SLICE WITH STEP PARAMETER
Extract every nth element, reverse sequences
"""
print("=== Basic Step Usage ===")
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(f"Original: {numbers}")
print(f"Every 2nd [::2]: {numbers[::2]}")
print(f"Every 3rd [::3]: {numbers[::3]}")
print(f"Every 4th [::4]: {numbers[::4]}")
print("\n=== Reverse with Negative Step ===")
# [::-1] reverses the sequence
print(f"Reversed [::-1]: {numbers[::-1]}")
text = "Python"
print(f"Text: {text}")
print(f"Reversed: {text[::-1]}")
print("\n=== Skip and Reverse ===")
# Every 2nd element, reversed
print(f"Every 2nd reversed [::2][::-1]: {numbers[::2][::-1]}")
# Or in one step:
print(f"Every 2nd reversed [::-2]: {numbers[::-2]}")
print("\n=== Extract Odd/Even Indices ===")
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
even_indices = data[::2] # Start at 0, step by 2
odd_indices = data[1::2] # Start at 1, step by 2
print(f"Data: {data}")
print(f"Even indices [::2]: {even_indices}")
print(f"Odd indices [1::2]: {odd_indices}")
print("\n=== Palindrome Checker ===")
def is_palindrome(text):
clean = text.lower().replace(" ", "")
return clean == clean[::-1]
words = ["racecar", "hello", "level", "python", "madam"]
for word in words:
result = "YES" if is_palindrome(word) else "NO"
print(f"{word}: {result}")
print("\n=== Every Third Starting at Index 1 ===")
sequence = list(range(20))
result = sequence[1::3]
print(f"From {sequence[:10]}...")
print(f"Every 3rd from index 1 [1::3]: {result}")
print("\n=== Practical: Sample Every 10th Data Point ===")
all_data = list(range(100))
sampled = all_data[::10]
print(f"Sampled 10 points from 100: {sampled}")