Skip to content

BASIC SLICE() EXAMPLES

Python
#!/usr/bin/env python3
"""
BASIC SLICE() EXAMPLES
Learn the fundamentals of slice objects and slicing
"""

print("=" * 60)
print("BASIC SLICE() - Understanding Slice Objects")
print("=" * 60)

# Example 1: Basic slice notation vs slice object
print("\n1. Slice Notation vs slice() Object")
print("-" * 40)

data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(f"Data: {data}\n")

# Traditional slice notation
result1 = data[2:7]
print(f"Using notation data[2:7]: {result1}")

# Using slice object
s = slice(2, 7)
result2 = data[s]
print(f"Using slice(2, 7):        {result2}")
print(f"Results are equal: {result1 == result2}")

# Example 2: Three forms of slice
print("\n2. Different slice() Forms")
print("-" * 40)

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Form 1: slice(stop)
s1 = slice(5)
print(f"slice(5):           {numbers[s1]}")

# Form 2: slice(start, stop)
s2 = slice(2, 8)
print(f"slice(2, 8):        {numbers[s2]}")

# Form 3: slice(start, stop, step)
s3 = slice(1, 9, 2)
print(f"slice(1, 9, 2):     {numbers[s3]}")

# Example 3: Slice attributes
print("\n3. Examining Slice Attributes")
print("-" * 40)

s = slice(2, 10, 3)
print(f"Slice object: slice(2, 10, 3)")
print(f"  start: {s.start}")
print(f"  stop:  {s.stop}")
print(f"  step:  {s.step}")

s_simple = slice(5)
print(f"\nSlice object: slice(5)")
print(f"  start: {s_simple.start}")
print(f"  stop:  {s_simple.stop}")
print(f"  step:  {s_simple.step}")

# Example 4: Why use slice objects?
print("\n4. Reusing Slice Objects")
print("-" * 40)

# Define once, use many times
first_three = slice(3)
middle_section = slice(3, 7)

fruits = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"]
numbers = [10, 20, 30, 40, 50, 60, 70]
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

print(f"Fruits:  {fruits}")
print(f"Numbers: {numbers}")
print(f"Letters: {letters}\n")

print(f"First three of fruits:  {fruits[first_three]}")
print(f"First three of numbers: {numbers[first_three]}")
print(f"First three of letters: {letters[first_three]}\n")

print(f"Middle section of fruits:  {fruits[middle_section]}")
print(f"Middle section of numbers: {numbers[middle_section]}")
print(f"Middle section of letters: {letters[middle_section]}")

# Example 5: Slicing strings
print("\n5. Slicing Strings")
print("-" * 40)

text = "Hello, World!"
print(f"Text: '{text}'\n")

first_five = slice(5)
last_six = slice(-6, None)  # None means "to the end"
every_other = slice(None, None, 2)

print(f"First 5 chars:  '{text[first_five]}'")
print(f"Last 6 chars:   '{text[last_six]}'")
print(f"Every other:    '{text[every_other]}'")

# Example 6: Common slice patterns
print("\n6. Common Slice Patterns")
print("-" * 40)

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(f"Data: {data}\n")

# All elements
all_elements = slice(None)
print(f"All elements:        {data[all_elements]}")

# First half
half = len(data) // 2
first_half = slice(half)
print(f"First half:          {data[first_half]}")

# Second half
second_half = slice(half, None)
print(f"Second half:         {data[second_half]}")

# Every second element
evens = slice(0, None, 2)
print(f"Every 2nd (0,2,4...): {data[evens]}")

# Odd positions
odds = slice(1, None, 2)
print(f"Every 2nd (1,3,5...): {data[odds]}")

# Example 7: Slicing from the end
print("\n7. Negative Indices in Slices")
print("-" * 40)

words = ["one", "two", "three", "four", "five", "six", "seven"]
print(f"Words: {words}\n")

# Last 3 elements
last_three = slice(-3, None)
print(f"Last 3:              {words[last_three]}")

# All except last 2
except_last_two = slice(None, -2)
print(f"Except last 2:       {words[except_last_two]}")

# From 3rd-to-last to 1st-to-last
slice_end = slice(-3, -1)
print(f"From -3 to -1:       {words[slice_end]}")

# Example 8: Step parameter (skip elements)
print("\n8. Using Step to Skip Elements")
print("-" * 40)

alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
print(f"Alphabet: {alphabet}\n")

every_3rd = slice(0, None, 3)
print(f"Every 3rd letter:    {alphabet[every_3rd]}")

every_5th = slice(0, None, 5)
print(f"Every 5th letter:    {alphabet[every_5th]}")

every_4th_from_2 = slice(2, None, 4)
print(f"Every 4th from C:    {alphabet[every_4th_from_2]}")

print("\n" + "=" * 60)
print("Key Concepts:")
print("  - slice(stop) - from beginning to stop")
print("  - slice(start, stop) - from start to stop")
print("  - slice(start, stop, step) - with custom step")
print("  - Slice objects can be stored and reused")
print("  - None means 'default' (beginning, end, or step of 1)")
print("  - Negative indices count from the end")
print("=" * 60)