
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Random Walk Implementation in Python
A random walk is a process where each step you take is determined randomly, often used to model unpredictable movement. which is used to characterize a path that consists of a sequence of random moves.
A simple random walk can be one-dimensional where a particle has to move either towards left or the right without any bias. With regards to the concept of random walk applied in higher dimensions like 2D, 3D and 4D, movement is made in random directions in the particular dimensions.
Each of the additional dimensions leads to additional difficulty of the walk and offers more information on random processes and space searching. These are theories with Python code for Random Walk in 1D, 2D, 3D, & 4D to explain how they can be simulated computer graphics.
Installation of Required Libraries
1. NumPy
The NumPy library for numerical computations in Python, useful for handling arrays and performing mathematical operations.
Syntax
pip install numpy
2. Matplotlib
The Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python.
Syntax
pip install matplotlib
Implementation of 1D Random Walk
The following code is for 1D random walk implementation in Python −
import numpy as np import matplotlib.pyplot as plt def random_walk_1d(steps): """Generate a 1D random walk.""" walk = np.zeros(steps) for i in range(1, steps): step = np.random.choice([-1, 1]) walk[i] = walk[i - 1] + step return walk # Number of steps steps = 1000 walk = random_walk_1d(steps) # Plot the random walk plt.figure(figsize=(10, 6)) plt.plot(walk, label='1D Random Walk') plt.xlabel('Steps') plt.ylabel('Position') plt.title('1D Random Walk') plt.legend() plt.show()
Output

Code Explanation
- Imports − numpy for numerical operations. matplotlib.pyplot for plotting the walk. random_walk_1d
-
Function − Creates a random walk in one dimension.
For each step, randomly decide to move left (-1) or right (+1).
Accumulates these steps to compute the position at each step. - Plotting − Plots the position against number of steps in order to visualise the random walk.
Implementation of 2D Random Walk
The following code is for 2D random walk implementation in Python −
import numpy as np import matplotlib.pyplot as plt def random_walk_2d(steps): """Generate a 2D random walk.""" positions = np.zeros((steps, 2)) for i in range(1, steps): step = np.random.choice(['up', 'down', 'left', 'right']) if step == 'up': positions[i] = positions[i - 1] + [0, 1] elif step == 'down': positions[i] = positions[i - 1] + [0, -1] elif step == 'left': positions[i] = positions[i - 1] + [-1, 0] elif step == 'right': positions[i] = positions[i - 1] + [1, 0] return positions # Number of steps steps = 1000 positions = random_walk_2d(steps) # Plot the random walk plt.figure(figsize=(10, 10)) plt.plot(positions[:, 0], positions[:, 1], label='2D Random Walk') plt.xlabel('X Position') plt.ylabel('Y Position') plt.title('2D Random Walk') plt.legend() plt.grid(True) plt.show()
Output

Code Explanation
Moves in one of the four ways − upwards, downwards, leftwards or rightwards. Updates the position accordingly and records each step.
Implementation of 3D Random Walk
The following code is for 3D random walk implementation in Python −
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def random_walk_3d(steps): """Generate a 3D random walk.""" positions = np.zeros((steps, 3)) for i in range(1, steps): step = np.random.choice(['x+', 'x-', 'y+', 'y-', 'z+', 'z-']) if step == 'x+': positions[i] = positions[i - 1] + [1, 0, 0] elif step == 'x-': positions[i] = positions[i - 1] + [-1, 0, 0] elif step == 'y+': positions[i] = positions[i - 1] + [0, 1, 0] elif step == 'y-': positions[i] = positions[i - 1] + [0, -1, 0] elif step == 'z+': positions[i] = positions[i - 1] + [0, 0, 1] elif step == 'z-': positions[i] = positions[i - 1] + [0, 0, -1] return positions # Number of steps steps = 1000 positions = random_walk_3d(steps) # Plot the random walk fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') ax.plot(positions[:, 0], positions[:, 1], positions[:, 2], label='3D Random Walk') ax.set_xlabel('X Position') ax.set_ylabel('Y Position') ax.set_zlabel('Z Position') ax.set_title('3D Random Walk') ax.legend() plt.show()
Output

Code Explanation
- Moves in one of six directions − x+, x-, y+, y-, z+, or z-. Updates the position in three dimensions.
- Plotting − 2D random walk is plotted with matplotlib. 3D random walk is plotted using mpl_toolkits.mplot3d for three-dimensional visualization.
Implementation of 4D Random Walk
The following code is for 4D random walk implementation in Python −
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def random_walk_4d(steps): """Generate a 4D random walk.""" positions = np.zeros((steps, 4)) for i in range(1, steps): direction = np.random.choice(['x+', 'x-', 'y+', 'y-', 'z+', 'z-', 'w+', 'w-']) if direction == 'x+': positions[i] = positions[i - 1] + [1, 0, 0, 0] elif direction == 'x-': positions[i] = positions[i - 1] + [-1, 0, 0, 0] elif direction == 'y+': positions[i] = positions[i - 1] + [0, 1, 0, 0] elif direction == 'y-': positions[i] = positions[i - 1] + [0, -1, 0, 0] elif direction == 'z+': positions[i] = positions[i - 1] + [0, 0, 1, 0] elif direction == 'z-': positions[i] = positions[i - 1] + [0, 0, -1, 0] elif direction == 'w+': positions[i] = positions[i - 1] + [0, 0, 0, 1] elif direction == 'w-': positions[i] = positions[i - 1] + [0, 0, 0, -1] return positions # Number of steps steps = 1000 positions = random_walk_4d(steps) # Plot a 4D random walk by projecting onto 3D fig = plt.figure(figsize=(10, 10)) # 3D projection using first three dimensions ax1 = fig.add_subplot(121, projection='3d') ax1.plot(positions[:, 0], positions[:, 1], positions[:, 2], label='Projection: X-Y-Z') ax1.set_xlabel('X Position') ax1.set_ylabel('Y Position') ax1.set_zlabel('Z Position') ax1.set_title('4D Random Walk (Projection)') ax1.legend() # Another 3D projection using last three dimensions ax2 = fig.add_subplot(122, projection='3d') ax2.plot(positions[:, 1], positions[:, 2], positions[:, 3], label='Projection: Y-Z-W') ax2.set_xlabel('Y Position') ax2.set_ylabel('Z Position') ax2.set_zlabel('W Position') ax2.set_title('4D Random Walk (Projection)') ax2.legend() plt.show()
Ouptut

Code Explanation
- random_walk_4d Function − Moves in one of eight directions: x+, x-, y+, y-, z+, z-, w+, w-. Updates the position in four dimensions.
- Plotting − Since 4D data is too complex to visualize directly, what we do is we map our 4D walk into 3D spaces that we can hopefully nicely visualize. The first subplot projects onto the X-Y-Z space. The second subplot projects onto the Y-Z-W space.
- Visualization − In these 3D projections it is clear how a walk evolves − you can have an idea about the behavior of the 4D walk from this.