Top 50 Python Programming Examples for Practice

Updated on August 23, 2024

Article Outline

Python is a popular programming language known for its simplicity and versatility. Many industries, such as web development, data science, automation, artificial intelligence, and more, use Python very effectively. It is always good to practise with Python program examples to enhance your logical understanding and programming skills.

 

In this article, we will learn various Python programming examples that you can practise to enhance your skills in Python. Many fundamental logics in the Python language are covered by these code examples. It includes sets, lists, dictionary entries, lists, strings, and many more.

What is Python?

This is a powerful language that works as a general-purpose language. Also, it provides different features that can be combined with other libraries. The interpreted nature of Python itself, dynamic typing, and beautiful syntax make it perfect for scripting and quick application development. It supports many platforms.

Features of Python

Python is known for its simplicity and readability among beginners. Python comes with various features that every user can leverage. Below are some of the key features of Python:

 

  • Python is an open-source language. This means that a copy of its code can be obtained online by any individual and contribute to developing a more feature-laden programming language.
  • Python has very basic syntax, similar to English, making it an easy language to read. It’s easy to learn a programming language because it’s a simple language.
  • Python defines its code chunks using indentation instead of curly braces.
  • The type of variables stated in the program are decided at runtime because it is a dynamically typed language.
  • Python is utilised in a variety of fields, such as web application development, data science, artificial intelligence, machine learning, and data analysis.
  • Python is an object-oriented language, it allows you to operate within a program just like an actual object would.
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Why Learn Python?

Learning Python in today’s time can be a great choice. Python is quite popular due to its large library, friendly & open-source community, and understandable syntax. Because of its simplicity and readability, it’s a great language for beginners, but experienced programmers may still use it to create advanced applications like machine learning apps, data science, etc. Python is used extensively across many different industries and it is a useful skill for job advancement.

Syntax

The given below is a basic syntax to write a Python program:

print(‘Hello, World!’)

In this example, the print statement is used to print a “Hello, World!” text. The syntax is straightforward, just like the English language.

 

Before we begin learning Python examples, let’s first understand some basics or prerequisites like data types or variables in Python.

 

  • Variables: Declaring variables explicitly is not necessary in Python. Values can be assigned directly.
  • Data Types: A variety of data types are supported by Python, including:
    • int: Whole numbers, such as 100.
    • float: Floating-point or decimal numbers, such as 3.14.
    • str: It is of string-type text, such as “Hello”.
    • bool: It is a boolean notation: True or False.
  • Comments:

For single-line comments, use (#), and for multi-line comments, use triple quotes (“`comment““).

Python Programming Examples

Basic Programs

To get familiar with Python, here are some of the basic programs that you can practise to move ahead with advanced programs.

 

1. Program to add two numbers.

 

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 sum

Output:

The sum of 2 numbers is: 320

2. Program to check whether a number is even or odd.

 

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 no if remainder is 0 else: print("The number is Odd") # Odd no if remainder is not 0

Output:

Enter a number: 252 The number is Even <strong> </strong>

3. Program to swap two numbers.

Code:

num1 = 56 # first number num2 = 90  # second number  print(f"The number 1 is {num1}, num2 = {num2}") # printing the original numbers  # swapping two numbers num1, num2 = num2, num1  print(f"Swapped numbers are: num1 = {num1}, num2 = {num2}") # printing the swapped numbers

Output:

The number 1 is 56, num2 = 90 Swapped numbers are: num1 = 90, num2 = 56  

4. Program to find the factorial of a number.

 

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 number

Output:

Enter a number to find factorial: 5 The Factorial of 5 is 120

5. Program to reverse a number.

 

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 results

Output:

Enter a number: 524512 Reversed Number Is: 215425

6. Program to check the prime 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: 25 The number 25 is prime: False

7. Program to find the GCD of two numbers.

# 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 numbers

Output:

Enter one number: 5 Enter second number: 10 GCD of 5 and 10 is 5

 

8. Program to find the sum of digits.

 

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: 8 <strong> </strong>

 

9. Program to check Armstrong number.

 

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 armstrong

Output:

Enter a number: 25551 The number 25551 is not an Armstrong number

Array Programs

An array is the best data structure to learn in programming. Practising the Python programs using arrays will make your fundamentals strong for lists and tuples. Here are some of the best Python programming examples of Arrays to practise.

 

10. Program to the maximum in an array.

 

Code:

arr = [45, 54, 76,123,25,123] # inputted array of numbers max_value = max(arr) # finding the max value of the max function print(f"The Maximum element in the array is: {max_value}") #printing the max element from array

Output:

The Maximum element in the array is: 123

11. Program to the minimum in an array.

 

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 element from array

Output:

The minimum element in the array is: 25

12. Program to find the sum of array elements.

 

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 sum of element in an array

Output:

The sum of elements in the array is: 446

13. Program to reverse the array elements.

 

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 array

Output:

The reversed array is: [123, 25, 123, 76, 54, 45]

14. Program to merge array elements.

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 array

Output:

The merged array is: [45, 54, 76, 123, 25, 123, 123, 25, 123, 76, 54, 45]

15. Program to remove duplicates from an array.

 

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 array

Output:

The reversed array is: [76, 45, 54, 25, 123]

16 Program to rotate array.

 

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 array

Output:

The rotated array is: [123, 25, 123, 45, 54, 76]

17. Program to find the second largest array element.

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}") # printing the second largest element of an array

Output:

The second largest element in the array is: 123

List Programs

The list is a versatile data structure in Python and includes multiple operations. Practising the programs using lists will make you understand how lists work in Python. Here are some of the best Python programming examples of List to practise.

 

18. Program to append elements to the list.

 

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 elements

Output:

The list after adding elements is: [56, 73, 12, 6876, 1257, 120, 1223, 609345]

19. Program to extend the list.

 

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 extending

Output:

The list extending the list 1 is: [56, 73, 12, 6876, 1257, 120, 1223, 98, 34, 23, 87, 1246, 123, 756]

20 Program to insert an element at the specific position.

 

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 element

Output:

The list after inserting an element is: [56, 73, 12, 6876, 85, 1257, 120, 1223]

21. Program to remove an element from the list.

 

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 removal

Output:

The list after removing an element is: [56, 12, 6876, 1257, 120, 1223]

22. Program to pop list element.

 

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 popping

Output:

The list after popping an element is: [56, 73, 12, 6876, 1257, 120]

23. Program to count occurrences of list elements.

 

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 number

Output:

The count of 73: 3

Matrix Programs

Matrices are used both in mathematics and programming. Practising the programs of matrix will help you learn the different operations of matrices in Python. Here are some of the best Python programming examples of matrix to practise.

 

24. Program to create a matrix.

 

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]

25. Program to transpose a matrix.

 

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]

26. Program to perform the addition and subtraction of two matrices.

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))] # Printing the matrix print("The addition of two matrices are:") # Using for-in to print the matrix 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))] # Printing the matrix print("The subtraction of two matrices are:")  # Using for-in to print the matrix 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]

27. Program to find matrix inversion.

 

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]

28. Program to find a trace of a matrix.

 

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: 158

String Programs

Strings are the most commonly used data type in programming. Practising the programs of strings will help you learn the string operations in Python. Here are some of the best Python programming examples of strings to practise.

 

29. Python program to check if a string is palindrome or not

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.

 

30. Python program to check whether the string is Symmetrical or Palindrome

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: True

 

31. Reverse words in a given String in Python

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 HeroVide!" print(f"The reversed words of the string {my_string} is: {rev(my_string)}")

Output:

The reversed words of the string Hello HeroVide! is: HeroVide! Hello

32. Program to remove Kth character from string in Python

 

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: HerVide

 

33. Program to check if a Substring is Present in a Given String

 

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 HeroVide" target = "HeroVide"  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 'HeroVide' is present in 'Welcome to HeroVide'.

Dictionary Programs

Key-value pairs, or dictionaries, are quite helpful in Python. Here are some of the best Python programming examples of dictionaries to practise.

 

34. Program to extract Unique values dictionary values

 

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}

 

35. Program to find the sum of all items 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: 1584

 

36. Program to remove a key from a dictionary

 

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}

 

37. Program to sort the list of dictionaries by values in Python using itemgetter.

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}]

 

38. Program to sort the list of dictionaries by values in Python using lambda

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}]

Tuple Programs

Tuples is an immutable sequential data structure that allows for storing collections of heterogeneous data. Here are some of the best Python programming examples of tuples to practice.

 

39. Program to find the size of a Tuple

 

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 bytes

 

40. Program to find the maximum and minimum K elements in Tuple

 

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 3 elements is: [8, 9, 10] The maximum 3 elements is: [12, 45, 46]

41. Program to create a list of tuples from a given list having a number and its cube in each tuple

 

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 tuple 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)]

42. Program to add a Tuple to the List

 

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))

43. Program to find the closest Pair to the Kth index element in the Tuple

 

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: 80

Searching and Sorting Programs

Searching and Sorting is the best way to learn about how various items in programming are sorted and how an element is searched. Here are some of the best searching and sorting programs to practise in Python.

 

44. Program for Binary Search

 

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  # Printing the searched element using binary search arr1 = [7, 8, 10, 2, 4, 80] target1 = 80 # element to search  # find the target 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   # find the target 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: 2

 

45. Program for Linear Search

 

Code:

# defining the binary search recursive 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   # find the target result1 = ls_iterative(arr1, target1) print(f"The element found using Linear Search at index: {result1}")

Output:

The element found using Linear Search at index: 4

46. Program for Insertion Sort

 

Code:

# defining the sorting function to sort the array def ins_sort(arr): # Traverse from 1 to the length of the array for i in range(1, len(arr)): key = arr[i] j = i - 1  # Move elements of arr[0..i-1] that are greater than key to 1 position ahead while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key  # Printing the sorted array arr = [7, 8, 10, 2, 4, 80] ins_sort(arr) print(f"The sorted array is: {arr}")

Output:

The sorted array is: [2, 4, 7, 8, 10, 80]

47. Program for QuickSort

 

Code:

# defining the sorting function to sort the array def find_partition(arr, low, high): i = low - 1 pivot = arr[high]  for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i]  arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1  def qs_sort(arr, low, high): if low < high: pi = find_partition(arr, low, high) qs_sort(arr, low, pi - 1) qs_sort(arr, pi + 1, high)  # Printing the sorted array arr = [7, 8, 10, 2, 4, 80] qs_sort(arr, 0, len(arr) - 1) print(f"The sorted array is: {arr}")

Output:

The sorted array is: [2, 4, 7, 8, 10, 80]

 48. Program for Selection Sort

 

Code:

# defining the sorting function to sort the array def sel_sort(arr): # Traverse through all array elements for i in range(len(arr)): min_idx = i for j in range(i + 1, len(arr)): if arr[j] < arr[min_idx]: min_idx = j arr[i], arr[min_idx] = arr[min_idx], arr[i]  # Printing the sorted array arr = [7, 8, 10, 2, 4, 80] sel_sort(arr) print(f"The sorted array is: {arr}")

Output:

The sorted array is: [2, 4, 7, 8, 10, 80]

49. Program for Bubble Sort

 

Code:

# defining the sorting function to sort the array def bb_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]  # Printing the sorted array arr = [7, 8, 10, 2, 4, 80] bb_sort(arr) <strong>print(f"The sorted array is: {arr}") </strong>

Output:

The sorted array is: [2, 4, 7, 8, 10, 80] <strong> </strong> <strong> </strong>

50. Program for Merge Sort

 

Code:

# defining the sorting function to sort the array def ms_sort(arr): if len(arr) > 1:  # find the midpoint mid = len(arr) // 2 left = arr[:mid] right = arr[mid:]  # sort the left part ms_sort(left) # sort the right part ms_sort(right)  i = j = k = 0  # run a while loop to check multiple cases while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1  while i < len(left): arr[k] = left[i] i += 1 k += 1  while j < len(right): arr[k] = right[j] j += 1 k += 1  # Printing the sorted array arr = [7, 8, 10, 2, 4, 80] ms_sort(arr) print(f"The sorted array is: {arr}")

Output:

The sorted array is: [2, 4, 7, 8, 10, 80]

Conclusion

In this article, we covered multiple Python programming examples for practice on various topics. The topics include basic, array programs, list programs, matrix programs, string, programs, etc. We have also covered using Python dictionary programs, tuple programs, and searching and sorting programs.

 

The examples discussed in this article provide a thorough manual for anyone wishing to practise and improve their Python skills, covering everything from simple string operations to advanced algorithms. Regardless of your level of programming experience, these examples will help you improve and advance your Python skills.

FAQs
Yes, this is possible in Python. Here we can have a matrix as a list of lists such that every inner list is a row. You could also exploit the numpy library which offers more potent methods of operating on matrices.
Python utilises dictionaries to store data in key-value pairs. These types of objects are mutable, do not have an order, and cannot contain duplicates. The values contained in these dictionaries can be accessed, updated, added, or removed through their keys.
Yes, Python is a very simple and easy-to-understand programming language. It’s used for various purposes because of its flexibility including web development, data science, artificial intelligence, and automation among others.
As for determining the “best” program written in Python; it depends on what you mean by best and the task at hand. For beginners, it is often advisable to start with a simple program such as “Hello World!”   If they are advanced users then they can go for complex projects such as web applications analysis scripts or machine learning models which will help them achieve their goals.
To write a Python program, one has to first install Python either locally or use an Online Compiler to write and run the program. To write a program, define the problem first and then write code to solve it before executing it. A Python-styled file may be edited using any plain-text editor and saved with a .py extension.

Updated on August 23, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved