Swap two elements in list Dry Run in PYTHON

Swap two elements in list is an interactive PYTHON dry run visualizer from the Lists programs section. Study the source code, then use the execution controls to follow each step, variable update, highlighted line, and console output.

This page provides a browser-based dry run with source-code highlighting, auto-scroll, voice narration controls, and execution output for learning the program step by step.

Swap two elements in list Program Code

# Swap two elements at given positions
arr = [1, 2, 3, 4, 5, 6, 7]
print("Original:", arr)

pos1, pos2 = 1, 4  # Swap index 1 (value 2) and index 4 (value 5)

# Using temporary variable
temp = arr[pos1]
arr[pos1] = arr[pos2]
arr[pos2] = temp
print(f"After swapping indices {pos1} and {pos2}: {arr}")

# Using tuple unpacking
arr2 = [1, 2, 3, 4, 5, 6, 7]
arr2[pos1], arr2[pos2] = arr2[pos2], arr2[pos1]
print(f"Using unpacking: {arr2}")

View the complete Lists programs page.

Program Console Swap two elements in list Topic: PYTHON Vignaankosh.com
Execution Panel
Step 0/0
Console is empty.