Python Programming Examples 50 Programs with Code and Output
Python is the most widely used programming language for beginners and one of the most productive tools for experienced developers. This page covers 50 Python programming examples with output, covering basic Python programs, array programs, list programs, matrix operations, string manipulation, dictionary programs, tuple programs, and searching and sorting algorithms. Every example includes the full Python code, the expected output, and a plain-English explanation of how the program works.
Whether you are looking for simple Python programs for beginners, Python programs for practice, or Python programs for interview preparation, this page covers the most searched examples in one place.

POSTGRADUATE PROGRAM IN
Multi Cloud Architecture & DevOps
Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems.
Table of Contents
Getting Started
- What is Python?
- Why Practise Python Programming Examples?
- How to Run Python Programs
Basic Python Programs (1–10)
- Python Hello World Program
- Add Two Numbers in Python
- Check Even or Odd Number
- Swap Two Variables
- Find Factorial of a Number
- Reverse a Number
- Check Prime Number
- Find GCD of Two Numbers
- Find Sum of Digits
- Check Armstrong Number
Python Array Programs (11–18)
- Find Maximum in an Array
- Find Minimum in an Array
- Find Sum of Array Elements
- Reverse an Array
- Merge Two Arrays
- Remove Duplicates from an Array
- Rotate an Array
- Find Second Largest Element
Python List Programs (19–24)
- Append Elements to a List
- Extend a List
- Insert an Element at a Specific Position
- Remove an Element from a List
- Pop an Element from a List
- Count Occurrences of an Element
Python Matrix Programs (25–29)
- Create a Matrix
- Transpose a Matrix
- Add and Subtract Two Matrices
- Find Matrix Inversion
- Find Trace of a Matrix
Python String Programs (30–34)
- Check if a String is a Palindrome
- Check if String is Symmetrical or Palindrome
- Reverse Words in a String
- Remove Kth Character from a String
- Check if a Substring is Present
Python Dictionary Programs (35–39)
- Extract Unique Values from a Dictionary
- Find Sum of All Items in a Dictionary
- Remove a Key from a Dictionary
- Sort Dictionary by Value Using itemgetter
- Sort Dictionary by Value Using Lambda
Python Tuple Programs (40–44)
- Find the Size of a Tuple
- Find Maximum and Minimum K Elements in a Tuple
- Create a List of Tuples with Number and its Cube
- Add a Tuple to a List
- Find Closest Pair to the Kth Index Element
Python Searching and Sorting Programs (45–50)
- Binary Search in Python
- Linear Search in Python
- Insertion Sort in Python
- Quick Sort in Python
- Selection Sort in Python
- Bubble Sort in Python
Reference Sections
- Python Programs by Difficulty Level
- Python Programs for Interview
- Frequently Asked Questions
What is Python?
Python is a high-level, interpreted, general-purpose programming language. It was created by Guido van Rossum and first released in 1991. Python is consistently ranked as the most popular programming language in the world. It is the primary language used in data science, machine learning, artificial intelligence, web development, automation, and scripting.
Python is known for its simple, readable syntax that reads close to plain English. A Python program typically requires fewer lines of code than the same logic written in Java or C++. This makes Python the most recommended first language for beginners and one of the most productive languages for professionals.
Key Features of Python
Simple syntax: Python code is clean, readable, and close to plain English, which reduces the learning curve for beginners and speeds up development for experienced programmers.
Interpreted language: Python executes code line by line without a compilation step, making it easy to write, test, and debug Python programs quickly.
Dynamically typed: Variables in Python do not require type declarations. The interpreter infers the type at runtime, which simplifies writing simple Python programs.
Extensive standard library: Includes built-in modules for file handling, mathematics, dates, regular expressions, networking, and much more, reducing the need for external dependencies.
Cross-platform: Python programs run on Windows, macOS, and Linux without modification.
Large ecosystem: Libraries and frameworks like NumPy, Pandas, Django, Flask, TensorFlow, and Scikit-learn make Python the dominant language in data science, web development, and AI.
Why Practise Python Programming Examples?
The most effective way to learn Python is to write Python code. Reading documentation or watching tutorials provides context, but only when you type a program, run it, and understand why it produces its output does the concept stick. Practising Python programs with output builds four skills simultaneously: problem-solving logic, Python syntax fluency, debugging ability, and code-reading speed. All four are tested directly in Python technical interviews.
Each example on this page is structured to maximise learning: a one-line description of what the program does, the complete Python code, the output, and a plain-English explanation of the logic. Start from Program 1 and work through in order, or jump to the section that matches what you’re practising.

82.9%
of professionals don't believe their degree can help them get ahead at work.
How to Run Python Programs
To run any Python program from this page, you need Python 3 installed on your machine. Download it from python.org. Once installed, copy the code into a file with a .py extension for example hello_world.py and run it from the terminal with the command: python hello_world.py. You can also use an online Python compiler to run programs directly in your browser without any installation.
Basic Python Programs
Basic Python programs cover the foundational concepts every programmer must know: print statements, variables, arithmetic operators, user input, conditional logic, loops, and functions. These are the most searched simple Python programs for beginners and form the building blocks for every more advanced program on this page.
1. Python Hello World Program
The Hello World program is the first Python program every beginner writes. It confirms that Python is installed correctly and demonstrates the print() function the most basic output operation in Python.
Code:
print('Hello, World!')Output:
Hello, World!How it works: The print() function takes a value and displays it on screen. Python reads the call, evaluates the string ‘Hello, World!’, and sends it to standard output. This is the simplest possible Python program. In Python 3, print() is always a function always use parentheses.
2. Add Two Numbers in Python
This program adds two numbers and prints the result. It demonstrates variable assignment, the addition operator, and f-string formatting three concepts used in almost every Python program.
Code:
num1 = 50 # input number 1
num2 = 270 # input number 2
sum = num1 + num2 # adding two numbers to get the sum
print(f"The sum of 2 numbers is: {sum}") # printing the sumOutput:
The sum of 2 numbers is: 320How it works: Python stores 50 and 270 in variables num1 and num2. The + operator adds them. The f-string uses curly braces to embed variable values directly inside the printed string Python substitutes them at runtime. This is cleaner and more readable than string concatenation with +.
3. Check Even or Odd Number
This program takes a number as input and checks whether it is even or odd. It uses the modulus operator (%) to check the remainder when divided by 2 a logic pattern that appears in many Python programs.
Code:
number = int(input("Enter a number: ")) # getting a number input to check for odd or even
# checking number using the remainder
if number % 2 == 0:
print("The number is Even") # Even if remainder is 0
else:
print("The number is Odd") # Odd if remainder is not 0Output:
Enter a number: 252
The number is EvenHow it works: The modulus operator % returns the remainder after division. Any even number divided by 2 gives remainder 0; any odd number gives 1. input() collects user input as a string and int() converts it to an integer so arithmetic works correctly.
4. Swap Two Variables
This program swaps the values of two variables using Python’s simultaneous assignment a single-line operation that requires no temporary variable, unlike most other programming languages.
Code:
num1 = 56 # first number
num2 = 90 # second number
print(f"The number 1 is {num1}, num2 = {num2}") # printing original numbers
# swapping two numbers
num1, num2 = num2, num1
print(f"Swapped numbers are: num1 = {num1}, num2 = {num2}") # printing swapped numbersOutput:
The number 1 is 56, num2 = 90
Swapped numbers are: num1 = 90, num2 = 56How it works: Python evaluates the entire right side before assigning to the left. So num2, num1 forms a temporary tuple (90, 56) and simultaneously assigns 90 to num1 and 56 to num2. In Java or C you would need a third temporary variable: temp = a; a = b; b = temp.
5. Find Factorial of a Number
The factorial of n is the product of all positive integers from 1 to n. For example, factorial(5) = 5 × 4 × 3 × 2 × 1 = 120. This program uses recursion, a function that calls itself to compute it.
Code:
# define a factorial function
def factorial(num):
if num == 0: # return 1 if num is 0
return 1
return num * factorial(num - 1) # return factorial of num
ans = int(input("Enter a number to find factorial: ")) # getting input to find factorial
print(f"The Factorial of {ans} is {factorial(ans)}") # printing factorial of a numberOutput:
Enter a number to find factorial: 5
The Factorial of 5 is 120How it works: factorial() calls itself with a smaller value each time. For factorial(5): 5 × factorial(4) → 4 × factorial(3) → down to the base case factorial(0) = 1. The call stack then unwinds and multiplies back up: 1 × 2 × 3 × 4 × 5 = 120. The base case (num == 0) is essential; without it the function would recurse forever and crash with a RecursionError.
6. Reverse a Number
This program takes a number as input and reverses its digits. For example, 524512 becomes 215425. It uses a while loop and the modulus operator to extract digits one at a time from the right.
Code:
num = int(input("Enter a number: ")) # getting input to reverse it
rev_num = 0 # initial variable with 0
# while loop until num is not 0
while num != 0:
digit = num % 10 # finding the remainder
rev_num = rev_num * 10 + digit
num //= 10
print(f"Reversed Number Is: {rev_num}") # printing the resultsOutput:
Enter a number: 524512
Reversed Number Is: 215425How it works: Modulus 10 extracts the last digit of num each iteration. That digit is appended to rev_num by multiplying rev_num by 10 and adding the digit. Integer division by 10 removes the last digit from num. The loop continues until num becomes 0, at which point rev_num holds the fully reversed number.
7. Check Prime Number
A prime number is greater than 1 and has no divisors other than 1 and itself. This program uses an efficient algorithm that only tests divisors up to the square root of the number.
Code:
# defining the prime check function
def prime_chk(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
ans = int(input("Enter a number to check for prime: "))
print(f"The number {ans} is prime: {prime_chk(ans)}")Output:
Enter a number to check for prime: 17
The number 17 is prime: TrueHow it works: If n has a divisor larger than its square root, it must also have one smaller so checking only up to the square root is both correct and faster than checking all values up to n. Numbers less than or equal to 1 are not prime by definition. If no divisor divides num evenly within the range, the function returns True.
8. Find GCD of Two Numbers
The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both without a remainder. This program uses the Euclidean algorithm, one of the oldest and most efficient algorithms in mathematics.
Code:
# defining the gcd function
def gcd(a, b):
while b:
a, b = b, a % b
return a
n1 = int(input("Enter one number: ")) # first input number
n2 = int(input("Enter second number: ")) # second input number
print(f"GCD of {n1} and {n2} is {gcd(n1, n2)}") # finding GCD of numbersOutput:
Enter one number: 5
Enter second number: 10
GCD of 5 and 10 is 5How it works: The algorithm replaces the larger number with the remainder of dividing the two. For gcd(10, 5): a=10, b=5 becomes a=5, b=0, which returns 5. The loop runs while b is non-zero. This runs in O(log min(a,b)) time far faster than checking all possible divisors.
9. Find Sum of Digits
This program calculates the sum of all individual digits in a number. For example, the digits of 251 add up to 2 + 5 + 1 = 8. This is a common Python program for beginners that practises loops and modulus arithmetic.
Code:
num = int(input("Enter any number: ")) # taking an input number
sum = 0
# while loop
while num != 0:
sum += num % 10 # adding sum with the remainder of input number
num //= 10
print(f"The sum of digits: {sum}")Output:
Enter any number: 251
The sum of digits: 8How it works: Modulus 10 extracts the last digit of num each iteration and adds it to the running sum. Integer division by 10 removes that digit. For 251: iteration 1 adds 1, iteration 2 adds 5, iteration 3 adds 2, giving a total of 8.
10. Check Armstrong Number
An Armstrong number (also called a narcissistic number) is a number equal to the sum of its digits each raised to the power of the number of digits. For example, 153 = 1³ + 5³ + 3³ = 153.
Code:
n = int(input("Enter a number: ")) # taking an input number
sum_cubes = sum(int(digit) ** 3 for digit in str(n)) # finding sum cubes
if n == sum_cubes:
print(f"The number {n} is an Armstrong number") # printing if n is armstrong
else:
print(f"The number {n} is not an Armstrong number") # printing if n is not armstrongOutput:
Enter a number: 153
The number 153 is an Armstrong numberHow it works: The generator expression converts n to a string to iterate over each digit character, converts each back to int, cubes it, and sums the results. For 153: 1³ + 5³ + 3³ = 1 + 125 + 27 = 153. A number like 25551 does not satisfy this condition and is not an Armstrong number.
Python Array Programs
Python array programs focus on performing operations on collections of elements finding max and min values, summing elements, reversing, merging, removing duplicates, and rotating arrays. In Python, arrays are typically implemented using lists. These examples cover the most searched array problems and the operations most commonly tested in Python technical interviews.
11. Find Maximum in an Array
This program finds the largest element in an array. It demonstrates Python’s built-in max() function the simplest way to find the maximum value in a list or array.
Code:
arr = [45, 54, 76, 123, 25, 123] # inputted array of numbers
max_value = max(arr) # finding the max value
print(f"The Maximum element in the array is: {max_value}") # printing the max elementOutput:
The Maximum element in the array is: 123How it works: max() iterates through all elements and returns the largest in O(n) time. For interview questions where built-in functions are not allowed, initialise a variable to arr[0] and update it inside a for loop whenever a larger value is found.
12. Find Minimum in an Array
This program finds the smallest element in an array using Python’s built-in min() function.
Code:
arr = [45, 54, 76, 123, 25, 123] # inputted array of numbers
min_value = min(arr) # finding the max value of the min function
print(f"The minimum element in the array is: {min_value}") # printing the min elementOutput:
The minimum element in the array is: 25How it works: min() scans every element and returns the smallest in O(n) time. Both min() and max() accept an optional key argument for custom comparison; for example, min(words, key=len) returns the shortest word in a list of strings.
13. Find Sum of Array Elements
This program calculates the total of all elements in an array using Python’s built-in sum() function.
Code:
arr = [45, 54, 76, 123, 25, 123] # inputted array of numbers
sum_of_arr = sum(arr) # finding the sum value of array elements
print(f"The sum of elements in the array is: {sum_of_arr}") # printing the sumOutput:
The sum of elements in the array is: 446How it works: sum() adds all elements in the iterable and returns the total. You can pass a starting value as the second argument: sum(arr, 10) would return 456. For large numerical arrays in data science applications, NumPy’s np.sum() is significantly faster.
14. Reverse an Array
This program reverses the order of all elements in an array using Python’s slice notation one of the most concise ways to reverse any sequence in Python.
Code:
arr = [45, 54, 76, 123, 25, 123] # inputted array of numbers
reversed_arr = arr[::-1] # finding the reverse array elements
print(f"The reversed array is: {reversed_arr}") # printing the reverse of elements in an arrayOutput:
The reversed array is: [123, 25, 123, 76, 54, 45]How it works: Slice notation [::-1] creates a new reversed copy the empty start and stop mean use the full list, and step -1 means step backwards. This does not modify the original array. To reverse in-place, use arr.reverse() instead.
15. Merge Two Arrays
This program combines two arrays into a single array using the + operator. Merging arrays is a common step in sorting algorithms and data processing.
Code:
arr1 = [45, 54, 76, 123, 25, 123] # inputted array 1 of numbers
arr2 = [123, 25, 123, 76, 54, 45] # inputted array 2 of numbers
merged_arrays = arr1 + arr2 # finding the merged array
print(f"The merged array is: {merged_arrays}") # printing the merged arrayOutput:
The merged array is: [45, 54, 76, 123, 25, 123, 123, 25, 123, 76, 54, 45]How it works: The + operator creates a new list with all elements of arr1 followed by arr2. It runs in O(n+m) time. arr1.extend(arr2) is an equivalent that modifies arr1 in-place. Use + when you need a new merged list; use extend() when you want to avoid creating an extra object.
16. Remove Duplicates from an Array
This program removes all duplicate elements from an array and returns only unique values. Removing duplicates is one of the most frequently asked Python interview questions.
Code:
arr = [45, 54, 76, 123, 25, 123] # inputted array of numbers
new_arr = list(set(arr)) # finding the new array with no duplicate elements
print(f"The reversed array is: {new_arr}") # printing the new elements in an arrayOutput:
The reversed array is: [76, 45, 54, 25, 123]How it works: Converting a list to a set removes duplicates automatically because sets only store unique values. Converting back to list gives the result. Note: sets are unordered so output order may differ from input. To preserve original insertion order while removing duplicates, use list(dict.fromkeys(arr)) this works in Python 3.7 and above.
17. Rotate an Array
This program rotates an array to the left by d positions elements from the front move to the back. Array rotation is a classic Python interview question that tests slice manipulation.
Code:
# defining the rotate function
def rotate(arr, d):
return arr[d:] + arr[:d] # rotating the array elements
arr = [45, 54, 76, 123, 25, 123] # inputted array of numbers
d = 3
print(f"The rotated array is: {rotate(arr, d)}") # printing the rotated arrayOutput:
The rotated array is: [123, 25, 123, 45, 54, 76]How it works: The function splits at position d: arr[d:] takes elements from d to end and arr[:d] takes elements from start to d. Concatenating them places the tail first, achieving a left rotation by d positions. For a right rotation, use arr[-d:] + arr[:-d].
18. Find Second Largest Element in an Array
This program finds the second largest element in an array. Finding the second largest without full sorting is one of the most commonly asked Python programming questions in technical interviews.
Code:
arr = [45, 54, 76, 123, 25, 123, 450] # inputted array of numbers
arr.remove(max(arr)) # removing the max element
sec_largest = max(arr) # finding the max element which is the second largest now
print(f"The second largest element in the array is: {sec_largest}") # printingOutput:
The second largest element in the array is: 123How it works: The approach removes the maximum element then finds the new maximum giving the second largest. Note: arr.remove() modifies the original array. For a cleaner solution that handles duplicates and preserves the original array, use sorted(set(arr))[-2].
Python List Programs
Python list programs cover the essential operations used in everyday Python development: appending, extending, inserting, removing, popping, and counting elements. Python lists are dynamic, ordered, and mutable; they are the most commonly used data structure in Python and appear in nearly every real-world Python program.
19. Append Elements to a List
This program adds a new element to the end of a list using the append() method, the most commonly used list method in Python.
Code:
user_list = [56, 73, 12, 6876, 1257, 120, 1223] # appending numbers in the list of numbers
user_list.append(609345)
print(f"The list after adding elements is: {user_list}") # printing the list in python after adding elementsOutput:
The list after adding elements is: [56, 73, 12, 6876, 1257, 120, 1223, 609345]How it works: append() adds exactly one element to the end of the list and modifies it in-place. It runs in O(1) amortised time. The key difference from extend(): append([1,2,3]) adds the entire list as a single nested element; extend([1,2,3]) unpacks it and adds 1, 2, and 3 as separate elements.
20. Extend a List
This program extends a list by adding all elements from a second list using the extend() method.
Code:
user_list_1 = [56, 73, 12, 6876, 1257, 120, 1223] # appending numbers in the list of numbers
user_list_2 = [98, 34, 23, 87, 1246, 123, 756] # appending numbers in the list of numbers
user_list_1.extend(user_list_2)
print(f"The list extending the list 1 is: {user_list_1}") # printing the list in python after extendingOutput:
The list extending the list 1 is: [56, 73, 12, 6876, 1257, 120, 1223, 98, 34, 23, 87, 1246, 123, 756]How it works: extend() iterates over the argument and appends each element individually. It modifies the list in-place and returns None. Unlike the + operator which creates a new list, extend() is more memory-efficient and preferred when adding elements to an existing list.
21. Insert an Element at a Specific Position
This program inserts a new element at a specific index in a list using insert(). This is useful when the order of elements matters.
Code:
user_list_1 = [56, 73, 12, 6876, 1257, 120, 1223] # appending numbers in the list of numbers
user_list_1.insert(4, 85)
print(f"The list after inserting an element is: {user_list_1}") # printing the list in python after inserting an elementOutput:
The list after inserting an element is: [56, 73, 12, 6876, 85, 1257, 120, 1223]How it works: insert(index, value) places value at the specified index and shifts all elements from that position one step to the right. Index 4 makes the new element the fifth item (0-indexed). insert() runs in O(n) time because of the shifting operation.
22. Remove an Element from a List
This program removes a specific value from a list using the remove() method. It removes the first occurrence of the value, not the element at an index.
Code:
user_list_1 = [56, 73, 12, 6876, 1257, 120, 1223] # appending numbers in the list of numbers
user_list_1.remove(73)
print(f"The list after removing an element is: {user_list_1}") # printing the list in python after removalOutput:
The list after removing an element is: [56, 12, 6876, 1257, 120, 1223]How it works: remove() finds and deletes the first occurrence of the specified value. If the value is not found, Python raises a ValueError. To remove by index instead of value, use del list[index] or pop(index). To safely avoid a ValueError, check first: if 73 in user_list_1: user_list_1.remove(73).
23. Pop an Element from a List
This program removes and returns the last element of a list using the pop() method.
Code:
user_list_1 = [56, 73, 12, 6876, 1257, 120, 1223] # appending numbers in the list of numbers
popped = user_list_1.pop()
print(f"The list after popping an element is: {user_list_1}") # printing the list in python after poppingOutput:
The list after popping an element is: [56, 73, 12, 6876, 1257, 120]How it works: pop() with no argument removes and returns the last element in O(1) time. pop(index) removes at a given position in O(n) time. A Python list used with append() and pop() behaves as a stack Last In, First Out. This is the standard way to implement a stack data structure in Python.
24. Count Occurrences of an Element in a List
This program counts how many times a specific value appears in a list using the count() method.
Code:
user_list_1 = [56, 73, 12, 73, 44, 73, 6876, 1257, 120, 1223] # appending numbers in the list of numbers
num = 73
cnt = user_list_1.count(num)
print(f"The count of {num}: {cnt}") # printing the list in python after counting a specific numberOutput:
The count of 73: 3How it works: count() scans the entire list and returns the number of times the value appears O(n) time. To count occurrences of multiple values efficiently in one pass, use collections.Counter: Counter(user_list_1) returns a dictionary mapping each value to its frequency.
Python Matrix Programs
Python matrix programs cover creating, transposing, and performing arithmetic on two-dimensional data structures. In Python, a matrix is represented as a list of lists. These examples are essential for learners moving into data science, numerical computing, and machine learning, where matrix operations are a daily requirement.
25. Create a Matrix in Python
This program creates a 3×3 matrix as a list of lists and prints each row on a separate line.
Code:
# defining a matrix
matrix = [
[45, 65, 23],
[90, 67, 12],
[65, 12, 46]
]
# Printing the matrix
print("The given matrix is:")
# Using for-in to print the matrix rows
for row in matrix:
print(row)Output:
The given matrix is:
[45, 65, 23]
[90, 67, 12]
[65, 12, 46]How it works: A matrix in Python is stored as a list of lists where each inner list represents one row. Access an individual element with matrix[row][column] for example, matrix[1][2] returns 12. The for loop iterates over each inner list. For large matrices and numerical computing, use NumPy arrays instead of lists of lists.
26. Transpose a Matrix
Transposing a matrix flips it along its main diagonal rows and columns become rows. Transposition is a fundamental operation in linear algebra and machine learning.
Code:
# defining a matrix
matrix = [
[45, 65, 23],
[90, 67, 12],
[65, 12, 46]
]
# Transposing the matrix
transp = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
# Printing the matrix
print("The given matrix is:")
# Using for-in to print the matrix rows
for row in transp:
print(row)Output:
The given matrix is:
[45, 90, 65]
[65, 67, 12]
[23, 12, 46]How it works: The nested list comprehension iterates over column indices in the outer loop and over each row in the inner loop, collecting element row[i] from each row. This turns the i-th column of the original into the i-th row of the transposed matrix. NumPy equivalent: np.array(matrix).T.
27. Add and Subtract Two Matrices
This program adds and subtracts two matrices element by element using list comprehensions the Python way to handle element-wise matrix arithmetic without external libraries.
Code:
# Defining the first matrix
m1 = [[45, 65, 23], [90, 67, 12], [65, 12, 46]]
# defining the second matrix
m2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
# Adding two matrices
addition_mat = [[m1[i][j] + m2[i][j] for j in range(len(m1[0]))] for i in range(len(m1))]
print("The addition of two matrices are:")
for row in addition_mat: print(row)
# subtracting two matrices
subtracting_mat = [[m1[i][j] - m2[i][j] for j in range(len(m1[0]))] for i in range(len(m1))]
print("The subtraction of two matrices are:")
for row in subtracting_mat: print(row)Output:
The addition of two matrices are:
[54, 73, 30]
[96, 72, 16]
[68, 14, 47]
The subtraction of two matrices are:
[36, 57, 16]
[84, 62, 8]
[62, 10, 45]How it works: The nested list comprehension performs the operation at position [i][j] for every row i and column j. Both matrices must have identical dimensions. NumPy simplifies this to np.array(m1) + np.array(m2) and np.array(m1) – np.array(m2) for any size matrix.
28. Find Matrix Inversion
The inverse of a matrix is another matrix that when multiplied with the original gives the identity matrix. This program computes the inverse of a 2×2 matrix using the standard mathematical formula.
Code:
# defining the matrix
matrix = [[1, 2], [4, 5]]
# Finding the determinant of the matrix
det = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
# Check if the determinant is non-zero
if det != 0:
# Calculate the inverse of the 2x2 matrix
inv = [
[matrix[1][1] / det, -matrix[0][1] / det],
[-matrix[1][0] / det, matrix[0][0] / det]
]
# Printing the inverse of the matrix
print("the inverse of the matrix is-")
for row in inv: print(row)
else:
print("The given matrix is singular and does not have an inverse")Output:
the inverse of the matrix is-
[-1.6666666666666667, 0.6666666666666666]
[1.3333333333333333, -0.3333333333333333]How it works: For a 2×2 matrix [[a,b],[c,d]], the inverse is (1/det) multiplied by [[d,-b],[-c,a]] where det = ad – bc. A determinant of 0 means the matrix is singular and has no inverse; the check prevents a division-by-zero error. For larger matrices, use np.linalg.inv(matrix).
29. Find Trace of a Matrix
The trace of a matrix is the sum of all elements on its main diagonal, the elements where the row index equals the column index.
Code:
# Defining the first matrix
m1 = [[45, 65, 23], [90, 67, 12], [65, 12, 46]]
# Calculate the trace of the matrix
ans_matrix = sum(m1[i][i] for i in range(len(m1))) # finding the trace i.e., sum of the diagonal elements
# print the matrix
print(f"Trace of the matrix: {ans_matrix}")Output:
Trace of the matrix: 158How it works: Diagonal elements are where row index equals column index: m1[0][0]=45, m1[1][1]=67, m1[2][2]=46. The generator expression sums them: 45+67+46=158. This only works for square matrices. NumPy equivalent: np.trace(m1).
Python String Programs
Python string programs cover the most searched string operations: palindrome check, substring search, reversing words, and character manipulation. Strings are immutable in Python every modification creates a new string object. String programs are the most frequently tested category in Python technical interviews.
30. Check if a String is a Palindrome
A palindrome is a string that reads the same forwards and backwards “level”, “racecar”, “madam”. Palindrome check is one of the most commonly asked Python string programs in interviews.
Code:
# defining the palindrome function
def palindrome_chk(string):
# Compare the string with its reverse
return string == string[::-1]
# Example usage
my_string = "level"
if palindrome_chk(my_string):
print(f"The string {my_string} is a palindrome.")
else:
print(f"The string {my_string} is not a palindrome.")Output:
The string level is a palindrome.How it works: Slice [::-1] creates a reversed copy of the string. Comparing the original with its reverse is the simplest Python palindrome check. For case-insensitive matching, use string.lower() == string.lower()[::-1]. To ignore spaces and punctuation, clean the string first: “”.join(c for c in s if c.isalnum()).lower().
31. Check if String is Symmetrical or Palindrome
This program checks two distinct string properties: symmetrical (first half equals second half) and palindrome (equals its reverse). “abba” is a palindrome but not symmetrical.
Code:
# defining the symm_chk function
def symm_chk(string):
# Check if the first half is equal to the second half
n = len(string)
return string[:n//2] == string[n//2:]
# defining the palindrome function
def palindrome_chk(string):
# Compare the string with its reverse
return string == string[::-1]
# Example usage
my_string = "abba"
print(f"The string {my_string} is symmetrical: {symm_chk(my_string)}")
print(f"The string {my_string} is palindrome: {palindrome_chk(my_string)}")Output:
The string abba is symmetrical: False
The string abba is palindrome: TrueHow it works: Symmetrical means the first half exactly equals the second half. For “abba”: first half = “ab”, second half = “ba” not equal, so not symmetrical. A palindrome means the full string equals its reverse: “abba” reversed is “abba” equal, so it is a palindrome. These are two distinct properties.
32. Reverse Words in a String
This program reverses the order of words in a sentence while keeping each word intact. “Hello World” becomes “World Hello”. This is a frequently tested Python string manipulation question.
Code:
# Defining function to reverse words
def rev(s):
# Split the string into words and reverse the word order
words = s.split()
rev = " ".join(reversed(words))
return rev
# Printing the reverse words of a string
my_string = "Hello HeroVired!"
print(f"The reversed words of the string {my_string} is: {rev(my_string)}")Output:
The reversed words of the string Hello HeroVired! is: HeroVired! HelloHow it works: split() with no argument splits on any whitespace and returns a list of words. reversed() yields them in reverse order. join() reassembles the words into a single string with spaces. A one-liner alternative: “ ”.join(s.split()[::-1]). Both handle multiple spaces correctly.
33. Remove Kth Character from a String
This program removes the character at a specific index from a string. Since Python strings are immutable, removing a character creates a new string.
Code:
# defining function to remove ith char
def remove_character(s, i):
# Remove the char at the ith position
return s[:i] + s[i+1:]
# Printing the new string
my_string = "HeroVide"
i = 3 # position for removal
print(f"The String {my_string} after removing the {i}-th character: {remove_character(my_string, i)}")Output:
The String HeroVide after removing the 3-th character: HerVideHow it works: s[:i] takes everything before index i and s[i+1:] takes everything after joining them skips the character at position i. Index 3 in “HeroVide” is “o”, so removing it gives “HerVide”. Python uses 0-based indexing: H=0, e=1, r=2, o=3.
34. Check if a Substring is Present in a String
This program checks whether one string appears inside another using the in operator the most Pythonic way to perform a substring search.
Code:
# defining the function to check for substring
def chk_subs(str, sub):
# Check if the substring is in the string
return sub in str
# Printing the string after checking the substring
my_str = "Welcome to HeroVired"
target = "HeroVired"
if chk_subs(my_str, target):
print(f"The substring '{target}' is present in '{my_str}'.")
else:
print(f"The substring '{target}' is not present in '{my_str}'.")Output:
The substring 'HeroVired' is present in 'Welcome to HeroVired'.How it works: The in operator returns True if the substring appears anywhere in the string. To get the position too, use str.find(sub) which returns the starting index or -1 if not found. str.index(sub) does the same but raises a ValueError when not found.
Python Dictionary Programs
Python dictionary programs cover storing, accessing, and manipulating key-value pairs. Dictionaries provide O(1) average-time lookup by key, making them one of the most important and versatile data structures in Python. Dictionary operations are tested in almost every Python interview.
35. Extract Unique Values from a Dictionary
This program extracts all unique values from a dictionary whose values are lists, using a set to remove duplicates.
Code:
# defining the function for checking unique values in the dictionary
def chk_unique(di):
# Extract unique values from dictionary values
ans = set(value for values in di.values() for value in values)
return ans
# Printing the dictionary values
di = {'A': [56, 45, 123], 'B': [123, 45, 2], 'C': [21, 45]}
ans = chk_unique(di) # adding the unique values in the ans
print(f"Unique values: {ans}")Output:
Unique values: {2, 45, 21, 56, 123}How it works: The generator uses two nested for loops: the outer iterates over each key’s list of values, the inner over each element in that list. Wrapping in set() removes duplicates. Output order may vary because sets are unordered. For a sorted result, use sorted(chk_unique(di)).
36. Find Sum of All Items in a Dictionary
This program calculates the total of all numeric values stored in a dictionary.
Code:
# defining the function for checking unique values in the dictionary
def find_sum(di):
# Calculating the sum of dictionary items
return sum(di.values())
# Printing the sum of items in a dictionary
di = {'a': 455, 'b': 455, 'c': 674}
ans = find_sum(di)
print(f"The sum of all items: {ans}")Output:
The sum of all items: 1584How it works: di.values() returns a view of all dictionary values. Passing this to sum() adds them together. This works when all values are numeric. Dictionary order is guaranteed in Python 3.7 and above values are returned in insertion order.
37. Remove a Key from a Dictionary
This program removes a specific key-value pair from a dictionary. It checks for key existence first to prevent a KeyError.
Code:
# defining the function for removing the key in the dictionary
def rem_key(di, key):
# Removing the specified key from the dictionary
if key in di:
del di[key]
return di
# Example usage
di = {'a': 34, 'b': 56, 'c': 6734}
key = 'c'
print(f"The values in the dictionary after removing key '{key}' is: {rem_key(di, key)}")Output:
The values in the dictionary after removing key 'c' is: {'a': 34, 'b': 56}How it works: del di[key] removes the key-value pair permanently. The ‘if key in di’ check prevents a KeyError when the key does not exist. A cleaner alternative: di.pop(key, None) removes the key if present and returns None if missing no prior check needed.
38. Sort List of Dictionaries by Value Using itemgetter
This program sorts a list of dictionaries by a specified key using itemgetter from the operator module one of the most common dictionary operations in Python data processing.
Code:
# importing the itemgetter from the operator
from operator import itemgetter
# defining the function for sorting the dictionary
def sorting_dict_item(my_list, key):
# Sort the list of dictionaries by the specified key using itemgetter
return sorted(my_list, key=itemgetter(key))
# Printing the sorted lists after sorting
my_list = [{'vehicle': 'BMW', 'year': 2025}, {'vehicle': 'Mercedes', 'year': 2022}, {'vehicle': 'Audi', 'year': 2023}]
print(f"Sorted list of dictionaries by 'year': {sorting_dict_item(my_list, 'year')}")Output:
Sorted list of dictionaries by 'year': [{'vehicle': 'Mercedes', 'year': 2022}, {'vehicle': 'Audi', 'year': 2023}, {'vehicle': 'BMW', 'year': 2025}]How it works: itemgetter(‘year’) creates a callable that retrieves the ‘year’ key from any dictionary. sorted() calls this on each item to determine order. To sort in descending order, add reverse=True to sorted().
39. Sort List of Dictionaries by Value Using Lambda
This program sorts a list of dictionaries by a specified key using a lambda function the inline alternative to itemgetter.
Code:
# defining the function for sorting the dictionary
def sorting_dict_item(my_list, key):
# Sort the list of dictionaries by the specified key using the lambda function in Python
return sorted(my_list, key=lambda x: x[key])
# Printing the sorted lists after sorting
my_list = [{'vehicle': 'BMW', 'year': 2025}, {'vehicle': 'Mercedes', 'year': 2022}, {'vehicle': 'Audi', 'year': 2023}]
print(f"Sorted list of dictionaries by 'year' using lambda: {sorting_dict_item(my_list, 'year')}")Output:
Sorted list of dictionaries by 'year' using lambda: [{'vehicle': 'Mercedes', 'year': 2022}, {'vehicle': 'Audi', 'year': 2023}, {'vehicle': 'BMW', 'year': 2025}]How it works: lambda x: x[key] takes a dictionary x and returns its value at the given key. sorted() calls this on each item to determine order. The output is identical to the itemgetter approach the choice between them is stylistic.
Python Tuple Programs
Python tuple programs cover operations on immutable ordered sequences. Tuples are faster than lists and are used when data should not change after creation. Because tuples are hashable, they can be used as dictionary keys and set elements something lists cannot do. These programs cover the most common tuple operations every Python learner needs.
40. Find the Size of a Tuple
This program finds the memory size of a tuple in bytes using the __sizeof__() method.
Code:
# defining the function to find tuple size
def my_tuple(item):
# Return the size of the tuple in bytes
return item.__sizeof__()
# Printing the size of the tuple
item = (56, 35, 66, 23, 87)
print(f"The size of the tuple is: {my_tuple(item)} bytes")Output:
The size of the tuple is: 64 bytesHow it works: __sizeof__() returns the memory size of the tuple object in bytes. To get the number of elements (not memory size), use len(item). Tuples are immutable: elements cannot be added, removed, or changed after creation. This immutability also makes them hashable and usable as dictionary keys, unlike lists.
41. Find Maximum and Minimum K Elements in a Tuple
This program extracts the K smallest and K largest elements from a tuple a common data selection operation in Python.
Code:
# defining the function to find max and min K elements
def max_min_k_elements(tup, k):
# sort the tuple and return the first and last k elements
sort_tuple = sorted(tup)
return sort_tuple[:k], sort_tuple[-k:]
# creating a tuple
tup = (8, 9, 10, 12, 46, 12, 45, 10)
# size of k
k = 2
# Finding the max and min elements from the function
min_k_tuple, max_k_tuple = max_min_k_elements(tup, k)
# printing the minimum and maximum elements
print(f"The minimum {k} elements is: {min_k_tuple}")
print(f"The maximum {k} elements is: {max_k_tuple}")Output:
The minimum 2 elements is: [8, 9]
The maximum 2 elements is: [45, 46]How it works: sorted() on a tuple returns a new sorted list. Slicing [:k] gives the k smallest elements and [-k:] gives the k largest. For large tuples where k is much smaller than the total length, heapq.nsmallest(k, tup) and heapq.nlargest(k, tup) are faster alternatives.
42. Create a List of Tuples with Number and its Cube
This program creates a list of tuples where each tuple pairs a number with its cube a practical example of building structured data with list comprehensions.
Code:
# defining the function
def my_function(lst):
# Convert a list to a list of tuples containing the number and their cube
return [(x, x**3) for x in lst]
# creating a list
list = [8, 9, 10, 12, 46, 12, 45, 10]
# Finding the cube of each list element
list_my = my_function(list)
# printing the minimum and maximum elements
print(f"List of tuples is: {list_my}")Output:
List of tuples is: [(8, 512), (9, 729), (10, 1000), (12, 1728), (46, 97336), (12, 1728), (45, 91125), (10, 1000)]How it works: The list comprehension (x, x**3) for x in lst creates a (number, cube) tuple for each element. x**3 is Python’s exponentiation operator. Pairing a value with a derived value is a pattern used frequently in sorting, lookup tables, and data transformation pipelines.
43. Add a Tuple to a List
This program demonstrates two operations: adding a tuple as a single element to a list, and merging a list into a tuple.
Code:
# defining the function to add a tuple to the list
def add_tp_ls(ls, tp):
# Add a tuple to the list
ls.append(tp)
return ls
# defining the function to add a list to a tuple
def add_ls_tp(tp, ls):
# Add a list to the tuple
return tp + tuple(ls)
# Defining list and tuple with values
ls = [10, 15, 20, 50]
tp = (40, 60, 70, 80)
print(f"The list after adding tuple: {add_tp_ls(ls, tp)}")
print(f"The tuple after adding list: {add_ls_tp(tp, ls)}")Output:
The list after adding tuple: [10, 15, 20, 50, (40, 60, 70, 80)]
The tuple after adding list: (40, 60, 70, 80, 10, 15, 20, 50, (40, 60, 70, 80))How it works: append(tp) adds the entire tuple as a single item. To unpack its elements individually instead, use extend(tp). For the reverse, tuple(ls) converts the list to a tuple and + concatenates both tuples into a new one. Tuples are immutable, so concatenation always creates a new tuple.
44. Find Closest Pair to the Kth Index Element in a Tuple
This program finds the element in a tuple that is numerically closest to the element at a given index.
Code:
# defining the function to find the closest pair
def find_cl_pair(tp, k):
# Find the closest pair to the k-th index element in the tuple
k_el = tp[k]
close = min(tp, key=lambda x: abs(x - k_el))
return k_el, close
# Defining list and tuple with values
tp = (40, 60, 70, 80)
k = 3
k_el, close = find_cl_pair(tp, k)
print(f"Element at index {k}: {k_el}")
print(f"Closest element to {k_el}: {close}")Output:
Element at index 3: 80
Closest element to 80: 80How it works: tp[k] retrieves the element at index k (which is 80). min(tp, key=lambda x: abs(x – k_el)) finds the element with the smallest absolute difference from k_el. Since 80 is in the tuple, the closest element to itself is itself.
Python Searching and Sorting Programs
Searching and sorting are the most tested algorithm categories in Python technical interviews. Understanding not just the code but the time complexity of each algorithm and when to use one over another is what interviewers evaluate. These examples cover the six most important searching and sorting algorithms every Python programmer must know.
45. Binary Search in Python
Binary search finds a target value in a sorted array by halving the search space each iteration. It runs in O(log n) time far faster than linear search for large datasets. This program shows both the recursive and iterative approaches.
Code:
# defining the binary search recursive function to search for an element
def bs_recursive(arr, start, end, target):
# Base case: If the element is not present
if end < start:
return -1
mid = (end + start) // 2
# If the element is present at the middle
if arr[mid] == target:
return mid
# If the element at mid is greater than the target
elif arr[mid] > target:
return bs_recursive(arr, start, mid - 1, target)
else:
return bs_recursive(arr, mid + 1, end, target)
def bs_iterative(arr, target):
start, end = 0, len(arr) - 1
while start <= end:
mid = (start + end) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
end = mid - 1
else:
start = mid + 1
return -1
arr1 = [7, 8, 10, 2, 4, 80]
target1 = 80 # element to search
result1 = bs_recursive(arr1, 0, 5, target1)
print(f"The element found using the Binary Search iterative approach is at index: {result1}")
arr2 = [7, 8, 10, 2, 4, 80]
target2 = 10 # element to search
result2 = bs_iterative(arr2, target2)
print(f"The element found using the Binary Search recursive approach is at index: {result2}")Output:
The element found using the Binary Search iterative approach is at index: 5
The element found using the Binary Search recursive approach is at index: 2How it works: Binary search only works on sorted arrays. Each iteration checks the middle element: if equal the search ends; if target is larger, search the right half (start = mid+1); if smaller, search the left half (end = mid-1). Each step halves the search space O(log n) time. For 1,000,000 elements, binary search needs at most 20 comparisons versus 1,000,000 for linear search.
46. Linear Search in Python
Linear search checks each element one by one from left to right until the target is found or the array ends. It works on both sorted and unsorted arrays and runs in O(n) time.
Code:
# defining the linear search function to search for an element
def ls_iterative(arr, target):
# Traverse through the array to find the element
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
# Printing the searched element using linear search
arr1 = [7, 8, 10, 2, 4, 80]
target1 = 4 # element to search
result = ls_iterative(arr1, target1)
print(f"The element found using Linear Search is at index: {result}")Output:
The element found using Linear Search is at index: 4How it works: Linear search visits each element in order and returns the index of the first match. Unlike binary search, it works on unsorted arrays. Best case is O(1) when the target is the first element. Worst case is O(n) when the target is last or not present. Use linear search for small or unsorted arrays.
47. Insertion Sort in Python
Insertion sort builds a sorted array one element at a time by inserting each new element into its correct position within the already-sorted portion similar to how you sort playing cards in your hand.
Code:
# defining the insertion sort function
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i] # element to place correctly
j = i - 1
# shift elements greater than key one position right
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
arr = [12, 11, 13, 5, 6]
print(f"Sorted array: {insertion_sort(arr)}")Output:
Sorted array: [5, 6, 11, 12, 13]How it works: For each element from index 1, the algorithm compares it with elements to its left and shifts each larger element one position right until the correct insertion point is found. Time complexity: O(n²) average, O(n) best case on already-sorted input. Insertion sort is a stable sort equal elements keep their original relative order.
48. Quick Sort in Python
Quick sort is a divide-and-conquer sorting algorithm. It picks a pivot element, partitions elements into groups smaller and larger than the pivot, then recursively sorts each group. Average time complexity: O(n log n).
Code:
# defining the quick sort function
def quick_sort(arr):
if len(arr) <= 1:
return arr # base case
pivot = arr[len(arr) // 2] # choose middle element as pivot
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
arr = [3, 6, 8, 10, 1, 2, 1]
print(f"Sorted array: {quick_sort(arr)}")Output:
Sorted array: [1, 1, 2, 3, 6, 8, 10]How it works: List comprehensions partition arr into three groups: less than, equal to, and greater than the pivot. The middle list handles duplicates correctly. Recursion sorts the left and right groups. A bad pivot choice (always smallest or largest) degrades performance to O(n²). Average time: O(n log n). This version uses O(n) extra space.
49. Selection Sort in Python
Selection sort divides the array into sorted and unsorted portions. It repeatedly finds the minimum element in the unsorted portion and swaps it into the next position of the sorted portion.
Code:
# defining the selection sort function
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i # assume first unsorted element is minimum
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j # update minimum index
arr[i], arr[min_idx] = arr[min_idx], arr[i] # swap
return arr
arr = [64, 25, 12, 22, 11]
print(f"Sorted array: {selection_sort(arr)}")Output:
Sorted array: [11, 12, 22, 25, 64]How it works: The inner loop finds the index of the minimum element in the unsorted portion. The outer loop swaps that minimum into position i. Selection sort makes exactly n-1 swaps regardless of input order useful when write operations are expensive. Time: O(n²) in all cases. Not a stable sort.
50. Bubble Sort in Python
Bubble sort repeatedly compares adjacent elements and swaps them if they are in the wrong order. After each pass through the array, the largest unsorted element moves to its correct position at the end.
Code:
# defining the bubble sort function
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j] # swap
return arr
arr = [64, 25, 12, 22, 11]
print(f"Sorted array: {bubble_sort(arr)}")Output:
Sorted array: [11, 12, 22, 25, 64]How it works: Two nested loops compare adjacent pairs and swap if out of order. After pass 1, the largest element is at the end. After pass 2, the two largest are in place, and so on. range(0, n-i-1) shrinks the inner loop each pass because the last i elements are already sorted. Time: O(n²) average and worst, O(n) best case with an early-exit flag.
Python Programs by Difficulty Level
If you are starting from scratch, follow this progression instead of working through programs in numerical order. It ensures every concept builds on the previous one.
Beginner Python Programs
Start here if you are new to Python or programming. These programs require only variables, operators, if-else statements, and basic loops.
Program 1 Hello World, Program 2 Add Two Numbers, Program 3 Even or Odd, Program 4 Swap Variables, Program 9 Sum of Digits, Program 11 Maximum in Array, Program 12 Minimum in Array, Program 13 Sum of Array Elements, Program 19 Append to List, Program 22 Remove Element from List.
Intermediate Python Programs
Move here after completing the beginner programs. These require functions, nested loops, recursion, and string slicing.
Program 5 Factorial using Recursion, Program 6 Reverse a Number, Program 7 Prime Number Check, Program 8 GCD of Two Numbers, Program 10 Armstrong Number, Program 14 Reverse Array, Program 16 Remove Duplicates, Program 29 Palindrome Check, Program 30 Reverse Words, Program 45 Binary Search, Program 46 Linear Search.
Advanced Python Programs
These programs require a strong understanding of algorithms, time complexity, and data structures. Essential for interview preparation.
Program 18 Second Largest Element, Program 25–28 Matrix Operations, Program 45 Binary Search, Program 47 Insertion Sort, Program 48 Quick Sort, Program 49 Selection Sort, Program 50 Bubble Sort.
Python Programs for Interview Preparation
Technical interviews at most companies test Python programs from four categories: string manipulation, array and list operations, recursion, and sorting algorithms. The programs most frequently asked are listed below with the reason interviewers ask them.
Most Asked Python Interview Programs
Check Armstrong Number (Program 10) Tests understanding of string-to-int conversion and generator expressions.
Remove Duplicates from Array (Program 16) Tests knowledge of sets versus lists and order preservation.
Find Second Largest Element (Program 18) Tests whether the candidate thinks about edge cases like duplicates.
Palindrome Check (Program 30) Tests string slicing and clean function design.
Reverse Words in a String (Program 32) Tests knowledge of split(), reversed(), and join().
Binary Search (Program 45) Tests divide-and-conquer logic and loop termination conditions.
Bubble Sort (Program 50) and Quick Sort (Program 48) Tests algorithm understanding; interviewers ask for both the code and the time complexity.
What Interviewers Evaluate
Writing correct code that produces the right output is the minimum requirement. Interviewers also evaluate: whether you choose the right data structure for the problem, whether you know the time complexity of your solution, whether you handle edge cases like empty arrays or duplicate values, and whether your code is readable. Practising all 50 programs in this list and writing each one from scratch without looking prepares you for all four dimensions.
Frequently Asked Questions
What are Python programming examples?
Python programming examples are working code samples that demonstrate how to solve specific problems using Python. They range from simple Python programs for beginners such as Hello World and adding two numbers to intermediate programs covering strings, arrays, and lists, to advanced programs covering sorting algorithms and matrix operations. Practising Python programs with output is the fastest way to build programming fluency because each example isolates one concept.
What is the best way to practise Python programs for beginners?
The best way to practise Python programs for beginners is to type each program manually, run it, check that the output matches, then close the code and try writing it again from scratch. This active recall approach rather than just reading the code is how syntax and logic become instinctive. Start with the 10 basic Python programs on this page, then move to list and string programs before attempting sorting algorithms.
Which Python programs are most commonly asked in technical interviews?
The most commonly asked Python programs in technical interviews include: palindrome check, remove duplicates from a list, find the second largest element, reverse a string without using reverse(), implement binary search, write a Fibonacci series using recursion, and implement bubble sort or quick sort. These programs test loop logic, data structure knowledge, string manipulation, and algorithm efficiency, the four areas that Python interviews focus on most.
What is the difference between simple Python programs and Python scripts?
A simple Python program typically means a short code example that demonstrates a single concept such as checking if a number is prime or reversing a string. A Python script is a .py file that runs from the command line to perform a task. In everyday usage, especially in learning contexts, the terms are used interchangeably. All 50 programs on this page can be saved as Python scripts and run from the terminal.
How many Python programs should I practise before applying for jobs?
Most entry-level Python roles expect fluency with 50 to 100 Python programs covering the topics in this page basic operations, data structures (lists, strings, dictionaries, tuples), and at least three sorting algorithms. For data science or machine learning roles, also practise matrix operations and NumPy-based programs. For software engineering roles, focus heavily on the sorting and searching section and practise explaining the time complexity of each algorithm.
Can I run Python programs online without installing Python?
Yes. Several free online Python compilers let you run Python programs directly in your browser without any installation. The most commonly used are programiz.com/python-programming/online-compiler, python.org/shell, and replit.com. These are useful for quickly testing programs from this page. For building real projects or running programs that use external libraries, installing Python 3 on your machine and using an IDE like VS Code is recommended.
Conclusion
This page covers 50 Python programming examples with code and output, organised across eight categories: basic programs, arrays, lists, matrices, strings, dictionaries, tuples, and searching and sorting algorithms. Every program includes the full Python code, the expected output, and a plain-English explanation of how it works the format that helps both learners and search engines understand the content.
If you are a beginner, start with Programs 1 to 10. If you are preparing for a Python technical interview, focus on strings, arrays, and the sorting section and make sure you can explain the time complexity of binary search, bubble sort, quick sort, insertion sort, and selection sort. The single most effective learning habit: after reading each program, close the page and write it from scratch. That step is what turns reading into skill.
Can we create a matrix in Python?
How are dictionaries used in Python?
Is Python a good programming language?
What is the best Python program?
How to write a Python program?
Updated on March 17, 2026
