Skip to content

SLICE FOR COPYING AND CLONING

Python
#!/usr/bin/env python3
"""
SLICE FOR COPYING AND CLONING
Create copies and modified versions of sequences
"""

print("=== Shallow Copy with Slice ===")
original = [1, 2, 3, 4, 5]
copy = original[:]  # Full slice creates a copy

copy.append(6)
print(f"Original: {original}")
print(f"Copy: {copy}")
print("Modifying copy doesn't affect original!")

print("\n=== Copy with Modification ===")
numbers = [10, 20, 30, 40, 50]

# Copy and reverse
reversed_copy = numbers[::-1]
print(f"Original: {numbers}")
print(f"Reversed copy: {reversed_copy}")

# Copy every other element
every_other = numbers[::2]
print(f"Every other: {every_other}")

print("\n=== Nested List Copy Issue ===")
matrix = [[1, 2], [3, 4], [5, 6]]

# Shallow copy - inner lists are still shared!
shallow = matrix[:]
shallow[0][0] = 999

print(f"Original matrix: {matrix}")
print(f"Shallow copy: {shallow}")
print("Both changed! Use copy.deepcopy() for nested structures.")

print("\n=== String Copying and Modification ===")
text = "Python"

# Strings are immutable, but slicing creates new objects
upper_copy = text[:].upper()
reverse_copy = text[::-1]

print(f"Original: {text}")
print(f"Uppercase copy: {upper_copy}")
print(f"Reversed copy: {reverse_copy}")

print("\n=== Clone and Extend ===")
base_list = [1, 2, 3]

# Create copy and extend it
extended = base_list[:] + [4, 5, 6]
doubled = base_list[:] * 2

print(f"Base: {base_list}")
print(f"Extended: {extended}")
print(f"Doubled: {doubled}")

print("\n=== Copy Specific Range ===")
data = list(range(1, 21))

# Copy specific sections
first_half = data[:len(data)//2]
second_half = data[len(data)//2:]
middle_third = data[len(data)//3:2*len(data)//3]

print(f"Data: {data}")
print(f"First half: {first_half}")
print(f"Second half: {second_half}")
print(f"Middle third: {middle_third}")

print("\n=== Defensive Copying in Functions ===")
def process_list(lst):
    # Copy to avoid modifying original
    working_copy = lst[:]
    working_copy.sort()
    working_copy.append(999)
    return working_copy

original = [5, 2, 8, 1, 9]
result = process_list(original)

print(f"Original unchanged: {original}")
print(f"Processed copy: {result}")