Python Programs

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 196

Python Programs

Last Updated : 14 Mar, 2024


Python Examples:
Practice with Python program examples is always a good choice to scale up your logical
understanding and programming skills and this article will provide you with the best sets of Python
code examples.
The below Python section contains a wide collection of Python programming examples. These
Python code examples cover a wide range of basic concepts in the Python language,
including List, Strings, Dictionary, Tuple, sets, and many more. Each program example
contains multiple approaches to solve the problem.
How to Add Two Numbers in Python – Easy
Programs
Last Updated : 22 Dec, 2023



Learn easy techniques and codes to add numbers in Python. Adding numbers in
Python is a very easy task, and we have provided you 7 different ways to add numbers
in Python.
Given two numbers num1 and num2. The task is to write a Python program to find the
addition of these two numbers.
Examples:
Input: num1 = 5, num2 = 3
Output: 8
Input: num1 = 13, num2 = 6
Output: 19
There are many methods to add two number in Python:
 Using “+” operator
 Defining a function that adds two number
 Using operator.add method
 Using lambda function
 Using Recursive function
Each of these methods have been explained with their program below.
Add Two Numbers with “+” Operator
Here num1 and num2 are variables and we are going to add both variables with the +
operator in Python.
 Python3

# Python3 program to add two numbers

num1 = 15

num2 = 12

# Adding two nos

sum = num1 + num2

# printing values

print("Sum of", num1, "and", num2 , "is", sum)

Output:
Sum of 15 and 12 is 27
We will now see Python programs to add two numbers without using + operator.
Add Two Numbers with User Input
In the below program to add two numbers in Python, the user is first asked to enter
two numbers, and the input is scanned using the Python input() function and stored in
the variables number1 and number2.
Then, the variable’s number1 and number2 are added using the arithmetic operator +,
and the result is stored in the variable sum.
 Python3

# Python3 program to add two numbers


number1 = input("First number: ")

number2 = input("\nSecond number: ")

# Adding two numbers

# User might also enter float numbers

sum = float(number1) + float(number2)

# Display the sum

# will print value in float

print("The sum of {0} and {1} is {2}" .format(number1,

number2, sum))

Output:
First number: 13.5 Second number: 1.54
The sum of 13.5 and 1.54 is 15.04
Add Two Numbers in Python Using Function
This program show adding two numbers in Python using function. We can define a
function that accepts two integers and returns their sum.
 Python3

#To define a function that take two integers

# and return the sum of those two numbers

def add(a,b):
return a+b

#initializing the variables

num1 = 10

num2 = 5

#function calling and store the result into sum_of_twonumbers

sum_of_twonumbers = add(num1,num2)

#To print the result

print("Sum of {0} and {1} is {2};" .format(num1,

num2, sum_of_twonumbers))

Output
Sum of 10 and 5 is 15;
Add Two Numbers Using operator.add() Method
Initialize two variables num1, and num2. Find sum using the operator.add() by
passing num1, and num2 as arguments and assign to su. Display num1,num2 and su
 Python3

# Python3 program to add two numbers


num1 = 15

num2 = 12

# Adding two nos

import operator

su = operator.add(num1,num2)

# printing values

print("Sum of {0} and {1} is {2}" .format(num1,

num2, su))

Output
Sum of 15 and 12 is 27
Read More: Operator Functions
Add Two Number Using Lambda Function
Here we are going to use Python Lambda function for addition of two number with
Python
 Python3

# Define a lambda function to add two numbers

add_numbers = lambda x, y: x + y

# Take input from the user


num1 = 1

num2 = 2

# Call the lambda function to add the two numbers

result = add_numbers(num1, num2)

# Print the result

print("The sum of", num1, "and", num2, "is", result)

Output:
The sum of 1 and 2 is 3
Add Two Numbers Using Recursive Function
This code defines a recursive function to add two numbers by incrementing one
number and decrementing the other. User inputs two numbers, and the sum is
calculated and displayed.
 Python3

# Define a recursive function to add two numbers

def add_numbers_recursive(x, y):

if y == 0:

return x

else:

return add_numbers_recursive(x + 1, y - 1)
# Take input from the user

num1 = 1

num2 = 2

# Call the recursive function to add the two numbers

result = add_numbers_recursive(num1, num2)

# Print the result

print("The sum of", num1, "and", num2, "is", result)

Output:
The sum of 1 and 2 is 3

So, without wasting your time start exploring the Python programs and scale up your logical
abilities in Python program.
Python Programming Tutorial
Recent Articles on Python !
Python Output & Multiple Choice Questions
Python Programming Examples Topics :
 Basic Programs
 Array Programs
 List Programs
 Matrix Programs
 String Programs
 Dictionary Programs
 Tuple Programs
 Searching and Sorting Programs
 Pattern Printing
 Date-Time Programs
 Regex Programs
 File Handling Programs
 More Python Programs

Basic Programs:
In this section, you will find all the basic Python programming examples. So, explore the section
and complete the basic stage of Python programming.
1. Python program to add two numbers
2. Maximum of two numbers in Python
3. Python Program for factorial of a number
4. Python Program for simple interest
5. Python Program for compound interest
6. Python Program to check Armstrong Number
7. Python Program for Program to find area of a circle
8. Python program to print all Prime numbers in an Interval
9. Python program to check whether a number is Prime or not
10. Python Program for n-th Fibonacci number
11. Python Program for How to check if a given number is Fibonacci number?
12. Python Program for n\’th multiple of a number in Fibonacci Series
13. Program to print ASCII Value of a character
14. Python Program for Sum of squares of first n natural numbers
15. Python Program for cube sum of first n natural numbers
Array Programs:
To scale up Array logic, try out the below-listed Python array programming examples. Here, you
will find all the important Python examples that are related to the Python array concept.
1. Python Program to find sum of array
2. Python Program to find largest element in an array
3. Python Program for array rotation
4. Python Program for Reversal algorithm for array rotation
5. Python Program to Split the array and add the first part to the end
6. Python Program for Find reminder of array multiplication divided by n
7. Python Program to check if given array is Monotonic
List Programs:
Explore the below section and try out all the important Python List programming examples.
1. Python program to interchange first and last elements in a list
2. Python program to swap two elements in a list
3. Python | Ways to find length of list
4. Python | Ways to check if element exists in list
5. Different ways to clear a list in Python
6. Python | Reversing a List
7. Python program to find sum of elements in list
8. Python | Multiply all numbers in the list
9. Python program to find smallest number in a list
10. Python program to find largest number in a list
11. Python program to find second largest number in a list
12. Python program to find N largest elements from a list
13. Python program to print even numbers in a list
14. Python program to print odd numbers in a List
15. Python program to print all even numbers in a range
16. Python program to print all odd numbers in a range
17. Python program to print positive numbers in a list
18. Python program to print negative numbers in a list
19. Python program to print all positive numbers in a range
20. Python program to print all negative numbers in a range
21. Remove multiple elements from a list in Python
22. Python – Remove empty List from List
23. Python | Cloning or Copying a list
24. Python | Count occurrences of an element in a list
25. Python | Remove empty tuples from a list
26. Python | Program to print duplicates from a list of integers
27. Python program to find Cumulative sum of a list
28. Python | Sum of number digits in List
29. Break a list into chunks of size N in Python
30. Python | Sort the values of first list using second list
More >>
Matrix Programs:
Get a detailed list of Python Matrix examples and boost your understanding of matrix concepts in
Python.
1. Python program to add two Matrices
2. Python program to multiply two matrices
3. Python program for Matrix Product
4. Adding and Subtracting Matrices in Python
5. Transpose a matrix in Single line in Python
6. Python | Matrix creation of n*n
7. Python | Get Kth Column of Matrix
8. Python – Vertical Concatenation in Matrix
String Programs:
If you are looking for Python programming examples that are based on the Python string concept,
then scroll down to the below section and practice a wide range of Python string program
examples.
1. Python program to check if a string is palindrome or not
2. Python program to check whether the string is Symmetrical or Palindrome
3. Reverse words in a given String in Python
4. Ways to remove i’th character from string in Python
5. Python | Check if a Substring is Present in a Given String
6. Python – Words Frequency in String Shorthands
7. Python – Convert Snake case to Pascal case
8. Find length of a string in python (4 ways)
9. Python program to print even length words in a string
10. Python program to accept the strings which contains all vowels
11. Python | Count the Number of matching characters in a pair of string
12. Remove all duplicates from a given string in Python
13. Python – Least Frequent Character in String
14. Python | Maximum frequency character in String
15. Python | Program to check if a string contains any special character
16. Generating random strings until a given string is generated
17. Find words which are greater than given length k
18. Python program for removing i-th character from a string
19. Python program to split and join a string
20. Python | Check if a given string is binary string or not
21. Python program to find uncommon words from two Strings
22. Python – Replace duplicate Occurrence in String
23. Python – Replace multiple words with K
24. Python | Permutation of a given string using inbuilt function
25. Python | Check for URL in a String
26. Execute a String of Code in Python
27. String slicing in Python to rotate a string
28. String slicing in Python to check if a string can become empty by recursive deletion
29. Python Counter| Find all duplicate characters in string
30. Python – Replace all occurrences of a substring in a string
More >>
Dictionary Programs:
In this section, you will find out all the important practice sets or examples related to the Python
Dictionary concept.
1. Python – Extract Unique values dictionary values
2. Python program to find the sum of all items in a dictionary
3. Python | Ways to remove a key from dictionary
4. Ways to sort list of dictionaries by values in Python – Using itemgetter
5. Ways to sort list of dictionaries by values in Python – Using lambda function
6. Python | Merging two Dictionaries
7. Python – Convert key-values list to flat dictionary
8. Python – Insertion at the beginning in OrderedDict
9. Python | Check order of character in string using OrderedDict( )
10. Dictionary and counter in Python to find winner of election
11. Python – Append Dictionary Keys and Values ( In order ) in dictionary
12. Python | Sort Python Dictionaries by Key or Value
13. Python – Sort Dictionary key and values List
14. Handling missing keys in Python dictionaries
15. Python dictionary with keys having multiple inputs
16. Print anagrams together in Python using List and Dictionary
17. K’th Non-repeating Character in Python using List Comprehension and OrderedDict
18. Check if binary representations of two numbers are anagram
19. Python Counter to find the size of largest subset of anagram words
20. Python | Remove all duplicates words from a given sentence
21. Python Dictionary to find mirror characters in a string
22. Counting the frequencies in a list using dictionary in Python
23. Python | Convert a list of Tuples into Dictionary
24. Python counter and dictionary intersection example (Make a string using deletion and
rearrangement)
25. Python dictionary, set and counter to check if frequencies can become same
26. Scraping And Finding Ordered Words In A Dictionary using Python
27. Possible Words using given characters in Python
28. Python – Keys associated with Values in Dictionary
More >>
Tuple Programs:
Explore the wide range of Tuple programs here in this section of Python programming examples.
1. Python program to Find the size of a Tuple
2. Python – Maximum and Minimum K elements in Tuple
3. Create a list of tuples from given list having number and its cube in each tuple
4. Python – Adding Tuple to List and vice – versa
5. Python – Closest Pair to Kth index element in Tuple
6. Python – Join Tuples if similar initial element
7. Python – Extract digits from Tuple list
8. Python – All pair combinations of 2 tuples
9. Python – Remove Tuples of Length K
10. Sort a list of tuples by second Item
11. Python program to Order Tuples using external List
12. Python – Flatten tuple of List to tuple
13. Python – Convert Nested Tuple to Custom Key Dictionary
More >>
Searching and Sorting Programs:
In this section, on searching and sorting examples, we have mentioned all the important example
sets of Python searching and sorting to boost your Python programming concept.
1. Python Program for Binary Search (Recursive and Iterative)
2. Python Program for Linear Search
3. Python Program for Insertion Sort
4. Python Program for Recursive Insertion Sort
5. Python Program for QuickSort
6. Python Program for Iterative Quick Sort
7. Python Program for Selection Sort
8. Python Program for Bubble Sort
9. Python Program for Merge Sort
10. Python Program for Iterative Merge Sort
11. Python Program for Heap Sort
12. Python Program for Counting Sort
13. Python Program for ShellSort
14. Python Program for Topological Sorting
15. Python Program for Radix Sort
16. Python Program for Binary Insertion Sort
17. Python Program for Bitonic Sort
18. Python Program for Comb Sort
19. Python Program for Pigeonhole Sort
20. Python Program for Cocktail Sort
21. Python Program for Gnome Sort
22. Python Program for Odd-Even Sort / Brick Sort
23. Python Program for BogoSort or Permutation Sort
24. Python Program for Cycle Sort
25. Python Program for Stooge Sort
Pattern Printing Programs:
Get a complete list of Python pattern printing examples in the below section.
1. Python Program to print the pattern ‘G’
2. Python Program to print an Inverted Star Pattern
3. Python Program to print double sided stair-case pattern
4. Python Program to print with your own font
Date-Time Programs:
In this section, we have mentioned all important Python program examples that are related to the
Python Date-Time concept.
1. Python program to get Current Time
2. Get Current Date and Time using Python
3. Python | Find yesterday’s, today’s and tomorrow’s date
4. Python program to convert time from 12 hour to 24 hour format
5. Python program to find difference between current time and given time
6. Python Program to Create a Lap Timer
7. Convert date string to timestamp in Python
8. How to convert timestamp string to datetime object in Python?
9. Find number of times every day occurs in a Year
Python Regex Programs:
To boost Python Regex concept get a list of Python Regex programming examples below.
1. Python Program to Check if String Contain Only Defined Characters using Regex
2. Python program to Count Uppercase, Lowercase, special character and numeric values
using Regex
3. Python Program to find the most occurring number in a string using Regex
4. Python Regex to extract maximum numeric value from a string
5. Python Program to put spaces between words starting with capital letters using Regex
6. Python – Check whether a string starts and ends with the same character or not
7. Python regex to find sequences of one upper case letter followed by lower case letters
8. Python Program to Remove duplicate words from Sentence
9. Python | Remove all characters except letters and numbers
10. Python Regex | Program to accept string ending with alphanumeric character
11. Python Regex – Program to accept string starting with vowel
12. Python Program to check if a string starts with a substring using regex
13. Python Program to Check if an URL is valid or not using Regular Expression
14. Parsing and Processing URL using Python – Regex
15. Python Program to validate an IP address using ReGex
16. Python Program to Check if email address valid or not
17. Python program to find files having a particular extension using RegEx
18. Python program to extract IP address from file
19. Python program to check the validity of a Password
20. Categorize Password as Strong or Weak using Regex in Python
Python File Handling Programs:
If you want to scale up your Python file handling concept, explore the below section and find out
all the real-life Python programming examples on Python file handling.
1. Python program to read file word by word
2. Python program to read character by character from a file
3. Python – Get number of characters, words, spaces and lines in a file
4. Python program to Count the Number of occurrences of a key-value pair in a text file
5. Python | Finding ‘n’ Character Words in a Text File
6. Python Program to obtain the line number in which given word is present
7. Count number of lines in a text file in Python
8. Python Program to remove lines starting with any prefix
9. Python Program to Eliminate repeated lines from a file
10. Python Program to read List of Dictionaries from File
11. Python – Append content of one text file to another
12. Python program to copy odd lines of one file to other
13. Python Program to merge two files into a third file
14. Python program to Reverse a single line of a text file
15. Python program to reverse the content of a file and store it in another file
16. Python Program to Reverse the Content of a File using Stack
More Popular Python Programs:
Find a more important or popular list of Python programming examples below and upscale your
Python programming skills.
1. Python Program to Reverse a linked list
2. Python Program for Find largest prime factor of a number
3. Python Program for Efficient program to print all prime factors of a given number
4. Python Program for Product of unique prime factors of a number
5. Python Program for Find sum of odd factors of a number
6. Python Program for Coin Change
7. Python Program for Tower of Hanoi
8. Python Program for Sieve of Eratosthenes
9. Python Program to Check if binary representation is palindrome
10. Python Program for Basic Euclidean algorithms
11. Python Program for Extended Euclidean algorithms
12. Python Program for Maximum height when coins are arranged in a triangle
13. Python Program for Find minimum sum of factors of number
14. Python Program for Difference between sums of odd and even digits
15. Python Program for Program to Print Matrix in Z form
16. Python Program for Smallest K digit number divisible by X
17. Python Program for Print Number series without using any loop
18. Python Program for Number of stopping station problem
19. Check if a triangle of positive area is possible with the given angles
20. Python program to find the most occurring character and its count
21. Python Program for Find sum of even factors of a number
22. Python Program for Check if all digits of a number divide it
23. Check whether a number has consecutive 0’s in the given base or not
24. Python Program for Number of solutions to Modular Equations
25. Python Program for Legendre\’s Conjecture
How to Add Two Numbers in Python – Easy
Programs
Last Updated : 22 Dec, 2023



Learn easy techniques and codes to add numbers in Python. Adding numbers in
Python is a very easy task, and we have provided you 7 different ways to add numbers
in Python.
Given two numbers num1 and num2. The task is to write a Python program to find the
addition of these two numbers.
Examples:
Input: num1 = 5, num2 = 3
Output: 8
Input: num1 = 13, num2 = 6
Output: 19
There are many methods to add two number in Python:
 Using “+” operator
 Defining a function that adds two number
 Using operator.add method
 Using lambda function
 Using Recursive function
Each of these methods have been explained with their program below.
Add Two Numbers with “+” Operator
Here num1 and num2 are variables and we are going to add both variables with the +
operator in Python.
 Python3

# Python3 program to add two numbers

num1 = 15

num2 = 12

# Adding two nos

sum = num1 + num2

# printing values

print("Sum of", num1, "and", num2 , "is", sum)

Output:
Sum of 15 and 12 is 27
We will now see Python programs to add two numbers without using + operator.
Add Two Numbers with User Input
In the below program to add two numbers in Python, the user is first asked to enter
two numbers, and the input is scanned using the Python input() function and stored in
the variables number1 and number2.
Then, the variable’s number1 and number2 are added using the arithmetic operator +,
and the result is stored in the variable sum.
 Python3

# Python3 program to add two numbers


number1 = input("First number: ")

number2 = input("\nSecond number: ")

# Adding two numbers

# User might also enter float numbers

sum = float(number1) + float(number2)

# Display the sum

# will print value in float

print("The sum of {0} and {1} is {2}" .format(number1,

number2, sum))

Output:
First number: 13.5 Second number: 1.54
The sum of 13.5 and 1.54 is 15.04
Add Two Numbers in Python Using Function
This program show adding two numbers in Python using function. We can define a
function that accepts two integers and returns their sum.
 Python3

#To define a function that take two integers

# and return the sum of those two numbers


def add(a,b):

return a+b

#initializing the variables

num1 = 10

num2 = 5

#function calling and store the result into sum_of_twonumbers

sum_of_twonumbers = add(num1,num2)

#To print the result

print("Sum of {0} and {1} is {2};" .format(num1,

num2, sum_of_twonumbers))

Output
Sum of 10 and 5 is 15;
Add Two Numbers Using operator.add() Method
Initialize two variables num1, and num2. Find sum using the operator.add() by
passing num1, and num2 as arguments and assign to su. Display num1,num2 and su
 Python3

# Python3 program to add two numbers


num1 = 15

num2 = 12

# Adding two nos

import operator

su = operator.add(num1,num2)

# printing values

print("Sum of {0} and {1} is {2}" .format(num1,

num2, su))

Output
Sum of 15 and 12 is 27
Read More: Operator Functions
Add Two Number Using Lambda Function
Here we are going to use Python Lambda function for addition of two number with
Python
 Python3

# Define a lambda function to add two numbers

add_numbers = lambda x, y: x + y
# Take input from the user

num1 = 1

num2 = 2

# Call the lambda function to add the two numbers

result = add_numbers(num1, num2)

# Print the result

print("The sum of", num1, "and", num2, "is", result)

Output:
The sum of 1 and 2 is 3
Add Two Numbers Using Recursive Function
This code defines a recursive function to add two numbers by incrementing one
number and decrementing the other. User inputs two numbers, and the sum is
calculated and displayed.
 Python3

# Define a recursive function to add two numbers

def add_numbers_recursive(x, y):

if y == 0:

return x

else:
return add_numbers_recursive(x + 1, y - 1)

# Take input from the user

num1 = 1

num2 = 2

# Call the recursive function to add the two numbers

result = add_numbers_recursive(num1, num2)

# Print the result

print("The sum of", num1, "and", num2, "is", result)

Output:
The sum of 1 and 2 is 3
Find Maximum of two numbers in Python
Last Updated : 03 Jul, 2023



Given two numbers, write a Python code to find the Maximum of these two numbers.
Examples:
Input: a = 2, b = 4
Output: 4
Input: a = -1, b = -4
Output: -1
Find Maximum of two numbers in Python
This is the naive approach where we will compare two numbers using if-
else statement and will print the output accordingly.
Example:
 Python3

# Python program to find the

# maximum of two numbers

def maximum(a, b):

if a >= b:

return a

else:

return b

# Driver code

a =2

b =4

print(maximum(a, b))

Output
4
Time complexity: O(1)
Auxiliary space: O(1)
Find Maximum of two numbers Using max() function
This function is used to find the maximum of the values passed as its arguments.
Example:
 Python3

# Python program to find the

# maximum of two numbers

a =2

b =4

maximum = max(a, b)

print(maximum)

Output
4
Time complexity: O(1)
Auxiliary space: O(1)
Maximum of two numbers Using Ternary Operator
This operator is also known as conditional expression are operators that evaluate
something based on a condition being true or false. It simply allows testing a
condition in a single line
Example:
 Python3

# Python program to find the

# maximum of two numbers

# Driver code

a =2

b =4

# Use of ternary operator

print(a if a >= b else b)

Output
4
Time complexity: O(1)
Auxiliary space: O(1)
Maximum of two numbers Using lambda function
 Python3

# python code to find maximum of two numbers

a=2;b=4
maximum = lambda a,b:a if a > b else b

print(f'{maximum(a,b)} is a maximum number')

Output:
4 is a maximum number
Maximum of two numbers Using list comprehension
 Python3

a=2;b=4

x=[a if a>b else b]

print("maximum number is:",x)

Output
maximum number is: [4]
Maximum of two numbers Using sort() method
 Python3

# Python program to find the

# maximum of two numbers

a =2

b =4

x=[a,b]

x.sort()
print(x[-1])

Output
4
Time Complexity : O(NlogN)
Auxiliary Space : O(1)
Python Program to Find the Factorial of a
Number
Last Updated : 26 Mar, 2024



Factorial of a non-negative integer, is multiplication of all integers smaller than or


equal to n.
For example factorial of 6 is 6*5*4*3*2*1 which is 720.
Find the Factorial of a Number Using Recursive approach
This Python program uses a recursive function to calculate the factorial of a given
number. The factorial is computed by multiplying the number with the factorial of its
preceding number.
python3
# Python 3 program to find
# factorial of given number
def factorial(n):

# single line to find factorial


return 1 if (n==1 or n==0) else n * factorial(n - 1)

# Driver Code
num = 5
print("Factorial of",num,"is",factorial(num))
Output:
Factorial of 5 is 120
Time Complexity: O(n)
Auxiliary Space: O(n)
Find the Factorial of a Number Using Iterative approach
Example 1:
python3
# Python 3 program to find
# factorial of given number
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact

# Driver Code
num = 5
print("Factorial of",num,"is",
factorial(num))

# This code is contributed by Dharmik Thakkar


Output:
Factorial of 5 is 120
Time Complexity: O(n)
Auxiliary Space: O(1)
Example 2:
Python3
# Python 3 program to find
# factorial of given number

# Function to find factorial of given number


def factorial(n):

res = 1

for i in range(2, n+1):


res *= i
return res
# Driver Code
num = 5
print("Factorial of", num, "is",
factorial(num))
Output
Factorial of 5 is 120

Time Complexity: O(n)


Auxiliary Space: O(1)
Find the Factorial of a Number Using One line Solution (Using Ternary
operator):
Python3
# Python 3 program to find
# factorial of given number

def factorial(n):

# single line to find factorial


return 1 if (n==1 or n==0) else n * factorial(n - 1)

# Driver Code
num = 5
print ("Factorial of",num,"is",
factorial(num))

# This code is contributed


# by Smitha Dinesh Semwal.
Output:
Factorial of 5 is 120
Time Complexity: O(n)
Auxiliary Space: O(n)
Find the Factorial of a Number Using using In-built function
In Python, math module contains a number of mathematical operations, which can be
performed with ease using the module. math.factorial() function returns the factorial
of desired number.
Syntax: math.factorial(x)
Parameter:
x: This is a numeric expression.
Returns: factorial of desired number.
Python3
# Python 3 program to find
# factorial of given number
import math

def factorial(n):
return(math.factorial(n))

# Driver Code
num = 5
print("Factorial of", num, "is",
factorial(num))

# This code is contributed by Ashutosh Pandit


Output:
Factorial of 5 is 120
Time complexity: O(N)
Auxiliary space: O(1)
Find the Factorial of a Number Using numpy.prod
Python3
import numpy
n=5
x=numpy.prod([i for i in range(1,n+1)])
print(x)
Output
120
Time Complexity: O(n)
Auxiliary Space: O(1)
Prime Factorization Method to find Factorial
1. Initialize the factorial variable to 1.
2. For each number i from 2 to n, do the following:
a. Find the prime factorization of i.
b. For each prime factor p and its corresponding power k in the factorization of i,
multiply the factorial variable by p raised to the power of k.
3. Return the factorial variable.
Python3
# Python 3 program to find factorial
# of a given number using prime
# factorization method.

# Function to find prime factors of a number


def primeFactors(n):
factors = {}
i = 2
while i*i <= n:
while n % i == 0:
if i not in factors:
factors[i] = 0
factors[i] += 1
n //= i
i += 1
if n > 1:
if n not in factors:
factors[n] = 0
factors[n] += 1
return factors

# Function to find factorial of a number


def factorial(n):
result = 1
for i in range(2, n+1):
factors = primeFactors(i)
for p in factors:
result *= p ** factors[p]
return result

# Driver Code
num = 5
print("Factorial of", num, "is", factorial(num))

Output
Factorial of 5 is 120

Time Complexity: O(sqrt(n))


Auxiliary Space: O(sqrt(n))
Python Program for Simple Interest
Last Updated : 21 Feb, 2024



Simple interest formula is given by: Simple Interest = (P x T x R)/100 Where, P is the
principal amount T is the time and R is the rate
Examples:
Input : P = 10000
R = 5
T = 5
Output :2500.0
We need to find simple interest on
Rs. 10,000 at the rate of 5% for 5
units of time.
Python Program for simple interest
 Python3

# Python3 program to find simple interest

# for given principal amount, time and

# rate of interest.

def simple_interest(p,t,r):

print('The principal is', p)

print('The time period is', t)

print('The rate of interest is',r)

si = (p * t * r)/100

print('The Simple Interest is', si)

return si
# Driver code

simple_interest(8, 6, 8)

Output
The principal is 8
The time period is 6
The rate of interest is 8
The Simple Interest is 3.84

Time complexity: O(1)


Auxiliary Space: O(1)
Program for simple interest with Taking input from user
We can calculate the simple interest by taking P,T and R from the user.
 Python3

# Python3 program to find simple interest

# principal amount, time and

# rate of interest taken from user.

def simple_interest(p,t,r):

print('The principal is', p)

print('The time period is', t)


print('The rate of interest is',r)

si = (p * t * r)/100

print('The Simple Interest is', si)

# Driver code

P = int(input("Enter the principal amount :"))

T = int(input("Enter the time period :"))

R = int(input("Enter the rate of interest :"))

simple_interest(P,T,R)

Output:
Input:
Enter the principal amount :3000
Enter the time period :7
Enter the rate of interest :1
Output:
The simple interest is 210.0
Time complexity: O(1)
Auxiliary Space: O(1)
Python Program for Compound Interest
Last Updated : 03 Jul, 2023



Let us discuss the formula for compound interest. The formula to calculate compound
interest annually is given by:
A = P(1 + R/100) t
Compound Interest = A – P
Where,
 A is amount
 P is the principal amount
 R is the rate and
 T is the time span
Find Compound Interest with Python
 Python3

# Python3 program to find compound

# interest for given values.

def compound_interest(principal, rate, time):

# Calculates compound interest

Amount = principal * (pow((1 + rate / 100), time))

CI = Amount - principal

print("Compound interest is", CI)


# Driver Code

compound_interest(10000, 10.25, 5)

Learn Data Structures & Algorithms with GeeksforGeeks

Output
Compound interest is 6288.946267774416

Time Complexity: O(1) since no loop is used the algorithm takes up constant time to
perform the operations
Auxiliary Space: O(1) since no extra array is used so the space taken by the
algorithm is constant.
Compound Interest with Input taking from user
In this method we are going to calculate the compound interest by taking input from
the user by using above formula.
 Python3

# Python3 program to find compound

# interest for input taking from user.

def compound_interest(principal, rate, time):

# Calculates compound interest


Amount = principal * (pow((1 + rate / 100), time))

CI = Amount - principal

print("Compound interest is", CI)

# Driver Code

#Taking input from user.

principal = int(input("Enter the principal amount: "))

rate = int(input("Enter rate of interest: "))

time = int(input("Enter time in years: " ))

#Function Call

compound_interest(principal,rate,time)

#This code is contributed by Vinay Pinjala.

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
Input:
Enter the principal amount: 3000
Enter rate of interest: 5
Enter time in years: 3
Output:
Compound interest is 472.875
Time Complexity: O(1) since no loop is used the algorithm takes up constant time to
perform the operations
Auxiliary Space: O(1) since no extra array is used so the space taken by the
algorithm is constant.
Finding compound interest of given values without using pow() function.
 Python3

# Python code

# To find compound interest

# inputs

p= 1200 # principal amount

t= 2 # time

r= 5.4 # rate

# calculates the compound interest

a=p*(1+(r/100))**t # formula for calculating amount

ci=a-p # compound interest = amount - principal amount

# printing compound interest value

print(ci)

Learn Data Structures & Algorithms with GeeksforGeeks

Output
133.0992000000001
Time Complexity: O(1) since no loop is used the algorithm takes up constant time to
perform the operations
Auxiliary Space: O(1) since no extra array is used so the space taken by the
algorithm is constant
Please refer complete article on Program to find compound interest for more details!
Compound Interest using for loop
 Python3

def compound_interest(principal, rate, time):

Amount = principal

for i in range(time):

Amount = Amount * (1 + rate/100)

CI = Amount - principal

print("Compound interest is", CI)

# Driver Code

compound_interest(1200, 5.4, 2)

#This code is contributed by Jyothi pinjala

Learn Data Structures & Algorithms with GeeksforGeeks

Output
Compound interest is 133.0992000000001

Time complexity: O(1)


Auxiliary Space: O(1)
Python Program to Check Armstrong Number
Last Updated : 23 Jun, 2023



Given a number x, determine whether the given number is Armstrong number or not.
A positive integer of n digits is called an Armstrong number of order n (order is
number of digits) if.
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
Example:
Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153

Input : 120
Output : No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9

Python Program to check Armstrong Number

 Python

# Python program to determine whether

# the number is Armstrong number or not

# Function to calculate x raised to

# the power y

def power(x, y):


if y == 0:

return 1

if y % 2 == 0:

return power(x, y // 2) * power(x, y // 2)

return x * power(x, y // 2) * power(x, y // 2)

# Function to calculate order of the number

def order(x):

# Variable to store of the number

n =0

while (x != 0):

n =n +1

x = x // 10

return n
# Function to check whether the given

# number is Armstrong number or not

def isArmstrong(x):

n = order(x)

temp = x

sum1 = 0

while (temp != 0):

r = temp % 10

sum1 = sum1 + power(r, n)

temp = temp // 10

# If condition satisfies

return (sum1 == x)

# Driver code
x = 153

print(isArmstrong(x))

x = 1253

print(isArmstrong(x))

Output
True
False
Time complexity: O((logn)2)
Auxiliary Space: O(1)

Python program to check if a number is an Armstrong number without using


the power function

A positive integer is called an Armstrong number if an Armstrong number of 3 digits,


the sum of cubes of each digit is equal to the number itself. For example, 153 is an
Armstrong number because
153 = 1*1*1 + 5*5*5 + 3*3*3
The while loop iterates like first, it checks if the number is not equal to zero or not. if
it is not equal to zero then enter into the loop and find the reminder of number ex:
153%10 gives reminder 3. In the next step add the cube of a number to the
sum1(3*3*3). Then the step gives the quotient of the number (153//10=15). this loop
will continue till the given number is equal to zero.

 Python3

# python 3 program
# to check whether the given number is armstrong or not

# without using power function

n = 153 # or n=int(input()) -> taking input from user

s =n # assigning input value to the s variable

b = len(str(n))

sum1 = 0

while n != 0:

r = n % 10

sum1 = sum1+(r**b)

n = n//10

if s == sum1:

print("The given number", s, "is armstrong number")

else:

print("The given number", s, "is not armstrong number")

# This code is contributed by Gangarajula Laxmi


Output
The given number 153 is armstrong number
Please refer complete article on Program for Armstrong Numbers for more details!
Time complexity: O(logn)
Auxiliary Space: O(1)

Python program to check if a number is an Armstrong number Using string


manipulation

This approach involves converting the input number into a string and iterating through
each digit in the string. For each digit, we raise it to the power of the number of digits
in the input number, and sum up the results. If the final sum equals the input number,
it is an Armstrong number.
Algorithm
1. Convert the input number into a string using str(num).
2. Find the length of the string using len(num_str) and store it in n.
3. Initialize a variable sum to zero.
4. Iterate through each digit in the string using a for loop, and convert each digit back
to an integer using int(digit).
5. Raise each digit to the power of n using int(digit)**n, and add the result to sum.
6. After the loop is complete, check whether sum is equal to num.
7. If sum is equal to num, return True (the input number is an Armstrong number).
8. If sum is not equal to num, return False (the input number is not an Armstrong
number).

 Python3

def is_armstrong(num):

num_str = str(num)

n = len(num_str)

sum = 0

for digit in num_str:


sum += int(digit)**n

if sum == num:

return True

else:

return False

num=153

print(is_armstrong(num))

Output
True
Time complexity: O(n), wheer n is length of number
Auxiliary Space: O(1)

Digit by digit sum approach to check for Armstrong number

1. Find the number of digits in the given number.


2. Initialize a variable sum to zero.
3. Extract each digit from the given number and raise it to the power of the number of
digits and add it to the sum.
4. If the sum is equal to the given number, then it is an Armstrong number, else it is
not. #include <iostream>

 Python3

import math
def isArmstrong(num):

n = num

numDigits = 0

sum = 0

# Find number of digits in num

while n > 0:

n //= 10

numDigits += 1

n = num

# Calculate sum of digits raised to the power of numDigits

while n > 0:

digit = n % 10

sum += math.pow(digit, numDigits)

n //= 10
# Check if num is Armstrong number or not

if sum == num:

return True

return False

# Example 1

num1 = 1634

if isArmstrong(num1):

print(num1, "is an Armstrong number.")

else:

print(num1, "is not an Armstrong number.")

# Example 2

num2 = 120

if isArmstrong(num2):

print(num2, "is an Armstrong number.")

else:

print(num2, "is not an Armstrong number.")

Output
1634 is an Armstrong number.
120 is not an Armstrong number.
Time Complexity: O(log n), where n is the given number.
Auxiliary Space: O(1)

Python program to check if a number is an Armstrong number in return


statement

Here’s a Python program to check if a number is an Armstrong number using just 3


lines of code:

 Python3

def is_armstrong_number(number):

return sum(int(digit)**len(str(number)) for digit in str(number)) == number

# Example usage:

num = 153

if is_armstrong_number(num):

print(f"{num} is an Armstrong number")

else:

print(f"{num} is not an Armstrong number")

Output
153 is an Armstrong number
Python Program to Find Sum of Array
Last Updated : 03 Jul, 2023



Given an array of integers, find the sum of its elements.


Examples:
Input : arr[] = {1, 2, 3}
Output : 6
Explanation: 1 + 2 + 3 = 6
This Python program calculates the sum of an array by iterating through each element
and adding it to a running total. The sum is then returned. An example usage is
provided to demonstrate the calculation of the sum for a given array.
Python Program to Find Sum of Array
Iterating through the array and adding each element to the sum variable and finally
displaying the sum.
 Python3

# Python 3 code to find sum

# of elements in given array

def _sum(arr):

# initialize a variable

# to store the sum

# while iterating through


# the array later

sum = 0

# iterate through the array

# and add each element to the sum variable

# one at a time

for i in arr:

sum = sum + i

return(sum)

# main function

if __name__ == "__main__":

# input values to list

arr = [12, 3, 4, 15]

# calculating length of array


n = len(arr)

# calling function ans store the sum in ans

ans = _sum(arr)

# display sum

print('Sum of the array is ', ans)

Output
Sum of the array is 34
Time complexity: O(n),
Auxiliary Space: O(1)
Python Program to Find Sum of Array Using sum()
Using the built-in function sum(). Python provides an inbuilt function sum() which
sums up the numbers in the list.
 Python3

# Python 3 code to find sum

# of elements in given array

# input values to list

arr = [12, 3, 4, 15]

# sum() is an inbuilt function in python that adds


# all the elements in list,set and tuples and returns

# the value

ans = sum(arr)

# display sum

print('Sum of the array is ', ans)

Output
Sum of the array is 34
Time complexity: O(n)
Auxiliary Space: O(1)
Python Program to Find Sum of Array Using reduce method
Using the reduce method. Array.reduce() method is used to iterate over the array and
get the summarized result from all elements of array.
 Python

from functools import reduce

# Python 3 code to find sum

# of elements in given array

def _sum(arr):
# iterate over array

# using reduce and get

# sum on accumulator

sum = reduce(lambda a, b: a+b, arr)

return(sum)

# driver function

arr = []

# input values to list

arr = [12, 3, 4, 15]

# calculating length of array

n = len(arr)

ans = _sum(arr)
# display sum

print('Sum of the array is ', ans)

Output
('Sum of the array is ', 34)
Time complexity : O(n)
Auxiliary Space : O(1)
Python Program to Find Sum of Array Using enumerate function
This code calculates the sum of elements in the list list1 using a loop. It iterates
through each element, adds it to the running sum s, and then prints the final sum.
 Python3

list1 = [12, 3, 4, 15];s=0

for i,a in enumerate(list1):

s+=a

print(s)

Output
34
Time complexity: O(n)
Auxiliary Space: O(1)
Python Program to Find Sum of Array Using Divide and conquer
Define a function that takes an array and two indices low and high. If low == high,
return the element at that index. Calculate the midpoint of the array as mid = (low +
high) // 2.Recursively find the sum of the left subarray as left_sum =
sum_of_array(arr, low, mid). Recursively find the sum of the right subarray as
right_sum = sum_of_array(arr, mid+1, high). Return the sum of the left and right
subarrays as left_sum + right_sum.
 Python3

def sum_of_array(arr, low, high):

if low == high:

return arr[low]

mid = (low + high) // 2

left_sum = sum_of_array(arr, low, mid)

right_sum = sum_of_array(arr, mid+1, high)

return left_sum + right_sum

#Examples

arr = [1, 2, 3]

print(sum_of_array(arr, 0, len(arr)-1)) # Output: 6

arr = [15, 12, 13, 10]

print(sum_of_array(arr, 0, len(arr)-1)) # Output: 50

Output
6
50
Please refer complete article on Program to find sum of elements in a given array for
more details!
Python Program to Find Sum of Array Using counter method.
This program finds the sum of an array using the Counter class from the collections
module in Python. The Counter class is used to count the occurrences of elements in
the input array. The program then iterates over the items in the counter and calculates
the sum of the array.
 Python3

from collections import Counter

arr = [12, 3, 4, 15]

c = Counter(arr)

sum = 0

for key, value in c.items():

sum += key * value

print("Sum of the array is", sum)

Output
Sum of the array is 34

Python Program to Find Largest Element in an


Array
Last Updated : 06 Mar, 2024



To find the largest element in an array, iterate over each element and compare it with
the current largest element. If an element is greater, update the largest element. At the
end of the iteration, the largest element will be found.
Given an array, find the largest element in it.
Input : arr[] = {10, 20, 4}
Output : 20
Input : arr[] = {20, 10, 20, 4, 100}
Output : 100
Find largest element in an array Using Native Approach
 Python3

# Python3 program to find maximum

# in arr[] of size n

# python function to find maximum

# in arr[] of size n

def largest(arr, n):

# Initialize maximum element

max = arr[0]
# Traverse array elements from second

# and compare every element with

# current max

for i in range(1, n):

if arr[i] > max:

max = arr[i]

return max

# Driver Code

arr = [10, 324, 45, 90, 9808]

n = len(arr)

Ans = largest(arr, n)

print("Largest in given array ", Ans)

Output
Largest in given array 9808
Time Complexity: O(N)
Auxiliary Space: O(1)
Find largest element in an array Using built-in function max()
Here we will use the inbuilt method max() to find the maximum of the array. Below is
the implementation of the approach.
 Python3

# Python3 program to find maximum

# in arr[] of size n

def largest(arr, n):

ans = max(arr)

return ans;

# Driver code

if __name__ == '__main__':

arr = [10, 324, 45, 90, 9808]

n = len(arr)

print ("Largest in given array ", largest(arr, n))

Output
Largest in given array 9808
Time Complexity: O(n), where n is length of list.
Auxiliary Space: O(1)
Find largest element in an array Using sort() function
Here we use the sort() function to sort the array. The largest element will be the last
element of the sorted array. Below is the implementation of the approach.
 Python3

# Python3 program to find maximum


# in arr[] of size n

def largest(arr, n):

# Sort the array

arr.sort()

# The last element of the

# array is the largest element

return arr[n-1]

# or return arr[-1]

# Driver Code

arr = [10, 324, 45, 90, 9808]

n = len(arr)

Ans = largest(arr, n)

print("Largest in given array ", Ans)


Output
Largest in given array 9808
Find largest element in an array Using reduce() function
Here we use the reduce() function to iterate over the array. We will find the largest
element the max function which will compare each element of array while iterating.
Below is the implementation of the above approach:
 Python3

# Python3 program to find maximum

# in arr[] of size n

from functools import reduce

def largest(arr):

# Sort the array

ans = reduce(max, arr)

return ans

# or returning largest value


# Driver Code

arr = [10, 324, 45, 90, 9808]

n = len(arr)

Ans = largest(arr)

print("Largest in given array ", Ans)

Output
Largest in given array 9808
Time complexity: O(n) where n is size of given array
Auxiliary space: O(1)
Please refer complete article on Program to find largest element in an array for more
details!
Find largest element in an array Using operator.gt()
Create a array of integers and assign it to the variable arr. Print the original array
using the print() function.Create an empty array and assign it to the variable arr1.
Sort the original array in descending order using the operator.gt() function and assign
the sorted array to the variable arr1. Print the biggest number in the array by accessing
the first element of the sorted array using arr1[0]. Print a message indicating that the
biggest number in the array has been found.

 Python3

# python program to find large number in the given array

import operator

# Initializing the list


arr = [2, 1, 7, 3, 0]

max=0

# printing the original list

print('The given array is:', arr)

#checking for large element

for i in arr:

if operator.gt(i,max):

max=i

# printing the large number in the array

print('The biggest number in the given array is:', max)

Output
The given array is: [2, 1, 7, 3, 0]
The biggest number in the given array is: 7
Time Complexity : O(n)
Auxiliary Space : O(1)
Find Largest Element with Python Lambda
In this program, we have an array called array with some elements. We use the max
function to find the largest element in the array. The key parameter is set to a lambda
function lambda x: x, which simply returns the element itself. This lambda function is
used to determine the comparison key for the max function.
 Python3

array = [10, 5, 20, 8, 15]

largest_element = max(array, key=lambda x: x)

print("Largest element in the array:", largest_element)

Output:
Largest element in the array: 20
Python Program for Array Rotation
Last Updated : 23 Jun, 2023



Here we are going to see how we can rotate array with Python code.
Array Rotation:
Python Program for Array Rotation Example
Partitioning the sub arrays and reversing them
Approach:
Input arr[] = [1, 2, 3, 4, 5, 6, 7, 8], d = 1, size = 8
1) Reverse the entire list by swapping first and last numbers
i.e start=0, end=size-1
2) Partition the first subarray and reverse the first subarray, by swapping first and
last numbers.
i.e start=0, end=size-d-1
3) Partition the second subarray and reverse the second subarray, by swapping first
and last numbers.
i.e start=size-d, end=size-1
Example:
 Python3

# Python program to left-rotate the given array

# Function reverse the given array

# by swapping first and last numbers.

def reverse(start, end, arr):

# No of iterations needed for reversing the list

no_of_reverse = end-start+1

# By incrementing count value swapping

# of first and last elements is done.

count = 0

while((no_of_reverse)//2 != count):

arr[start+count], arr[end-count] = arr[end-count], arr[start+count]


count += 1

return arr

# Function takes array, length of

# array and no of rotations as input

def left_rotate_array(arr, size, d):

# Reverse the Entire List

start = 0

end = size-1

arr = reverse(start, end, arr)

# Divide array into twosub-array

# based on no of rotations.

# Divide First sub-array

# Reverse the First sub-array


start = 0

end = size-d-1

arr = reverse(start, end, arr)

# Divide Second sub-array

# Reverse the Second sub-array

start = size-d

end = size-1

arr = reverse(start, end, arr)

return arr

arr = [1, 2, 3, 4, 5, 6, 7, 8]

size = 8

d =1

print('Original array:', arr)

# Finding all the symmetric rotation number


if(d <= size):

print('Rotated array: ', left_rotate_array(arr, size, d))

else:

d = d % size

print('Rotated array: ', left_rotate_array(arr, size, d))

# This code contributed by SR.Dhanush

Output
Original array: [1, 2, 3, 4, 5, 6, 7, 8]
Rotated array: [2, 3, 4, 5, 6, 7, 8, 1]
Time Complexity: O(log10(Half no of elements presents in the given array)).
Auxiliary Space: O(1).
Python Program for Array Rotation Using temp array
Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements.

Rotation of the above array by 2 will make array


Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2, n =7
1) Store d elements in a temp array
temp[] = [1, 2]
2) Shift rest of the arr[]
arr[] = [3, 4, 5, 6, 7, 6, 7]
3) Store back the d elements
arr[] = [3, 4, 5, 6, 7, 1, 2]

 Python3

# function to rotate array by d elements using temp array

def rotateArray(arr, n, d):

temp = []

i =0

while (i < d):

temp.append(arr[i])

i =i +1

i =0

while (d < n):

arr[i] = arr[d]

i =i +1

d =d +1

arr[:] = arr[: i] + temp


return arr

# Driver function to test above function

arr = [1, 2, 3, 4, 5, 6, 7]

print("Array after left rotation is: ", end=' ')

print(rotateArray(arr, len(arr), 2))

Output
Array after left rotation is: [3, 4, 5, 6, 7, 1, 2]
Time complexity: O(n)
Auxiliary Space: O(d)
Python Program for Array Rotation Using Rotate one by
one
leftRotate(arr[], d, n)
start
For i = 0 to i < d
Left rotate all elements of arr[] by one
end
To rotate by one, store arr[0] in a temporary variable temp, move arr[1] to arr[0],
arr[2] to arr[1] …and finally temp to arr[n-1]
Let us take the same example arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2
Rotate arr[] by one 2 times We get [2, 3, 4, 5, 6, 7, 1] after first rotation and [ 3, 4, 5,
6, 7, 1, 2] after second rotation.

 Python3
#Function to left rotate arr[] of size n by d*/

def leftRotate(arr, d, n):

for i in range(d):

leftRotatebyOne(arr, n)

#Function to left Rotate arr[] of size n by 1*/

def leftRotatebyOne(arr, n):

temp = arr[0]

for i in range(n-1):

arr[i] = arr[i+1]

arr[n-1] = temp

# utility function to print an array */

def printArray(arr,size):

for i in range(size):

print ("%d"% arr[i],end=" ")


# Driver program to test above functions */

arr = [1, 2, 3, 4, 5, 6, 7]

leftRotate(arr, 2, 7)

printArray(arr, 7)

# This code is contributed by Shreyanshi Arun

Output
3 4 5 6 7 1 2
Time complexity : O(n * d)
Auxiliary Space : O(1)
Python Program for Array Rotation Using 4 Juggling Algorithm
This is an extension of method 2. Instead of moving one by one, divide the array in
different sets
where number of sets is equal to GCD of n and d and move the elements within sets.
If GCD is 1 as is for the above example array (n = 7 and d =2), then elements will be
moved within one set only, we just start with temp = arr[0] and keep moving arr[I+d]
to arr[I] and finally store temp at the right place.
Here is an example for n =12 and d = 3. GCD is 3 and
Let arr[] be {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

a) Elements are first moved in first set – (See below diagram for
this movement
arr[] after this step --> {4 2 3 7 5 6 10 8 9 1 11 12}

b) Then in second set.


arr[] after this step --> {4 5 3 7 8 6 10 11 9 1 2 12}

c) Finally in third set.


arr[] after this step --> {4 5 6 7 8 9 10 11 12 1 2 3}

 Python3

# Function to left rotate arr[] of size n by d

def leftRotate(arr, d, n):

for i in range(gcd(d, n)):

# move i-th values of blocks

temp = arr[i]

j =i

while 1:

k =j +d
if k >= n:

k =k -n

if k == i:

break

arr[j] = arr[k]

j =k

arr[j] = temp

# UTILITY FUNCTIONS

# function to print an array

def printArray(arr, size):

for i in range(size):

print("%d" % arr[i], end=" ")

# Function to get gcd of a and b


def gcd(a, b):

if b == 0:

return a

else:

return gcd(b, a % b)

# Driver program to test above functions

arr = [1, 2, 3, 4, 5, 6, 7]

leftRotate(arr, 2, 7)

printArray(arr, 7)

Output
3 4 5 6 7 1 2
Time complexity : O(n)
Auxiliary Space : O(1)
Another Approach : Using List slicing
 Python3

# Python program using the List


# slicing approach to rotate the array

def rotateList(arr,d,n):

arr[:]=arr[d:n]+arr[0:d]

return arr

# Driver function to test above function

arr = [1, 2, 3, 4, 5, 6]

print(arr)

print("Rotated list is")

print(rotateList(arr,2,len(arr)))

# this code is contributed by virusbuddah

Output
[1, 2, 3, 4, 5, 6]
Rotated list is
[3, 4, 5, 6, 1, 2]
If array needs to be rotated by more than its length then mod should be done.
For example: rotate arr[] of size n by d where d is greater than n. In this case d%n
should be calculated and rotate by the result after mod.
Time complexity : O(n) where n is size of given array
Auxiliary Space : O(1)
Python Program for Reversal algorithm for
array rotation
Last Updated : 26 Mar, 2024



Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. In this


article, we will explore the Reversal Algorithm for array rotation and implement it
in Python.
Example
Input: arr[] = [1, 2, 3, 4, 5, 6, 7]
d = 2
Output: arr[] = [3, 4, 5, 6, 7, 1, 2]

Rotation of the above array by 2 will make an array

Python Program for Reversal Algorithm of Array Rotation


Python3
# Function to reverse arr[]
def rverseArray(arr,d):
c=(arr[d:])+(arr[:d])
return c
# Driver function to test above functions
arr = [1, 2, 3, 4, 5, 6, 7]
d=2
print(rverseArray(arr,d))

Output
[3, 4, 5, 6, 7, 1, 2]
Python Program for Reversal algorithm for Array Rotation
Python3
# Python program for reversal algorithm of array rotation

# Function to reverse arr[] from index start to end


def rverseArray(arr, start, end):
while (start < end):
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start += 1
end = end-1

# Function to left rotate arr[] of size n by d


def leftRotate(arr, d):
n = len(arr)
rverseArray(arr, 0, d-1)
rverseArray(arr, d, n-1)
rverseArray(arr, 0, n-1)
# Function to print an array
def printArray(arr):
for i in range(0, len(arr)):
print (arr[i])
# Driver function to test above functions
arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2) # Rotate array by 2
printArray(arr)

Output
3
4
5
6
7
1
2
Python Program for Reversal Algorithm Using collections.deque
Python3
from collections import deque

def rotate_array_deque(arr, d):


n = len(arr)
rotated_array = deque(arr)
rotated_array.rotate(-d)
return list(rotated_array)

# Example
arr = [1, 2, 3, 4, 5, 6, 7]
d = 2

rotated_array = rotate_array_deque(arr, d)
print("Rotated array:", rotated_array)

Output
Rotated array: [3, 4, 5, 6, 7, 1, 2]
Time complexity: O(n + k).
Auxiliary space: O(n)
Python Program to Split the array and add the
first part to the end
Last Updated : 28 Mar, 2023



There is a given array and split it from a specified position, and move the first part of
the array add to the end.

Examples:
Input : arr[] = {12, 10, 5, 6, 52, 36}
k = 2
Output : arr[] = {5, 6, 52, 36, 12, 10}
Explanation : Split from index 2 and first
part {12, 10} add to the end .
Input : arr[] = {3, 1, 2}
k = 1
Output : arr[] = {1, 2, 3}
Explanation : Split from index 1 and first
part add to the end.
Method 1:
 Python3

# Python program to split array and move first

# part to end.

def splitArr(arr, n, k):

for i in range(0, k):

x = arr[0]

for j in range(0, n-1):

arr[j] = arr[j + 1]

arr[n-1] = x

# main

arr = [12, 10, 5, 6, 52, 36]

n = len(arr)
position = 2

splitArr(arr, n, position)

for i in range(0, n):

print(arr[i], end=' ')

# Code Contributed by Mohit Gupta_OMG <(0_o)>

Output
5 6 52 36 12 10
Time complexity: O(nk), where n is the length of the array and k is the number of
times the first part of the array needs to be moved to the end.
Auxiliary space: O(1), the program only uses a constant amount of additional
memory.
Method 2:
 Python3

# Python program to split array and move first

# part to end.

def splitArr(a, n, k):


b = a[:k]

return (a[k::]+b[::])

# main

arr = [12, 10, 5, 6, 52, 36]

n = len(arr)

position = 2

arr = splitArr(arr, n, position)

for i in range(0, n):

print(arr[i], end=' ')

Output
5 6 52 36 12 10
Time Complexity: O(n), where n is the length of the input array ‘arr’.
Auxiliary Space: O(k), where k is the value of ‘position’ input parameter.
Method 3: Using slicing and extend() methods
 Python3

# Python program to split array and move first

# part to end.
arr = [12, 10, 5, 6, 52, 36]

n = len(arr)

position = 2

x = arr[:position]

y = arr[position:]

y.extend(x)

for i in y:

print(i, end=" ")

Output
5 6 52 36 12 10
Time complexity: O(n)
Auxiliary space: O(n)
Method 4: Using list comprehension and modulo:
Another approach is to split an array into two parts and add the first part to the end of
the second part. This operation is commonly used in programming and can be useful
for a variety of applications, such as rotating the elements of an array or implementing
circular buffers.
 Define the function split_and_add(arr, n) that takes an array arr and an integer n as
input.
 Compute the length of the input array using the len function and store it in a
variable arr_len.
 Use a list comprehension to create a new list result of the same length as the input
array, where each element of the new list is computed using the formula (i + n) %
arr_len where i is the index of the current element in the input array.
 Return the new list result.
 Python3

def split_and_add(arr, n):


return [arr[(i + n) % len(arr)] for i in range(len(arr))]

arr = [12, 10, 5, 6, 52, 36]

n =2

result = split_and_add(arr, n)

print(*result)

Output
5 6 52 36 12 10

Python Program for Find remainder of array


multiplication divided by n
Last Updated : 04 Dec, 2023



Write a Python program for a given multiple numbers and a number n, the task is to
print the remainder after multiplying all the numbers divided by n.
Examples:
Input: arr[] = {100, 10, 5, 25, 35, 14},
n = 11
Output: 9
Explanation: 100 x 10 x 5 x 25 x 35 x 14 = 61250000 % 11 = 9
Input : arr[] = {100, 10},
n=5
Output : 0
Explanation: 100 x 10 = 1000 % 5 = 0
Python Program to Find remainder of array multiplication
divided by n using Naive approach:
First multiple all the number then take % by n then find the remainder, But in this
approach, if the number is maximum of 2^64 then it give the wrong answer.
Below is the implementation of the above approach:
 Python3

# This code finds the remainder of the product of all the elements in the array arr
divided by 'n'.

def findremainder(arr, len, n):

product = 1

for i in range(len):

product = product * arr[i]

return product % n

arr = [100, 10, 5, 25, 35, 14]

len = len(arr)

n = 11

print(findremainder(arr, len, n))

Learn Data Structures & Algorithms with GeeksforGeeks


Output
9

Time Complexity: O(n)


Auxiliary Space: O(1)
Approach that avoids overflow :
First take a remainder or individual number like arr[i] % n. Then multiply the
remainder with current result. After multiplication, again take remainder to avoid
overflow. This works because of distributive properties of modular arithmetic. ( a * b)
%c=((a%c)*(b%c))%c
Below is the implementation of the above approach:
 Python3

# Python3 program to

# find remainder when

# all array elements

# are multiplied.

# Find remainder of arr[0] * arr[1]

# * .. * arr[n-1]

def findremainder(arr, lens, n):

mul = 1

# find the individual


# remainder and

# multiple with mul.

for i in range(lens):

mul = (mul * (arr[i] % n)) % n

return mul % n

# Driven code

arr = [ 100, 10, 5, 25, 35, 14 ]

lens = len(arr)

n = 11

# print the remainder

# of after multiple

# all the numbers

print( findremainder(arr, lens, n))

# This code is contributed by "rishabh_jain".

Learn Data Structures & Algorithms with GeeksforGeeks


Output
9

Time Complexity: O(len), where len is the size of the given array
Auxiliary Space: O(1)
Approach by using the functools.reduce method
We have used the reduce function from the functools module to iteratively multiply
all elements in the input array and calculate the remainder after each multiplication
operation when divided by the given number n.
Below is implementation for the above approach:
 Python3

from functools import reduce

def remainderAfterMultiplication(arr, n):

result = reduce(lambda x, y: (x * y) % n, arr)

return result

# Driver Code

arr1 = [100, 10, 5, 25, 35, 14]

n1 = 11

result1 = remainderAfterMultiplication(arr1, n1)

print(result1)
arr2 = [100, 10]

n2 = 5

result2 = remainderAfterMultiplication(arr2, n2)

print(result2)

Learn Data Structures & Algorithms with GeeksforGeeks

Output
9
0

Time Complexity: O(len), where len is the size of the given array
Auxiliary Space: O(1)
Python Program to check if given array is
Monotonic
Last Updated : 26 Mar, 2024



Given an array A containing n integers. The task is to check whether the array
is Monotonic or not. An array is monotonic if it is either monotone
increasing or monotone decreasing. An array A is monotone increasing if for all i
<= j, A[i] <= A[j].
An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return Type: Boolean value, “True” if the given array A is monotonic else return
“False” (without quotes).
Examples:
Input : 6 5 4 4
Output : true
Input : 5 15 20 10
Output : false
Approach : Using extend() and sort()
 First copy the given array into two different arrays using extend()
 Sort the first array in ascending order using sort()
 Sort the second array in descending order using sort(reverse=True)
 If the given array is equal to any of the two arrays then the array is monotonic
Python3
# Check if given array is Monotonic
def isMonotonic(A):
x, y = [], []
x.extend(A)
y.extend(A)
x.sort()
y.sort(reverse=True)
if(x == A or y == A):
return True
return False

# Driver program
A = [6, 5, 4, 4]

# Print required result


print(isMonotonic(A))

Output
True
Time Complexity: O(N*logN), where N is the length of the array.
Auxiliary space: O(N), extra space is required for lists x and y.
Approach:
An array is monotonic if and only if it is monotone increasing, or monotone
decreasing. Since p <= q and q <= r implies p <= r. So we only need to check
adjacent elements to determine if the array is monotone increasing (or decreasing),
respectively. We can check each of these properties in one pass.
To check whether an array A is monotone increasing, we’ll check A[i] <= A[i+1] for
all i indexing from 0 to len(A)-2. Similarly we can check for monotone
decreasing where A[i] >= A[i+1] for all i indexing from 0 to len(A)-2.
Note: Array with single element can be considered to be both monotonic increasing
or decreasing, hence returns “True“.
Below is the implementation of the above approach:
Python3
# Python Program to check if given array is Monotonic
# Check if given array is Monotonic

def isMonotonic(A):

return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or


all(A[i] >= A[i + 1] for i in range(len(A) - 1)))

# Driver program
A = [6, 5, 4, 4]

# Print required result


print(isMonotonic(A))

Output
True
Time Complexity: O(N), where N is the length of the array.
Auxiliary space: O(1) because it is using constant space.
Approach 3 – By checking length of the array
Python3
def isMonotonic(arr):
if len(arr) <= 2:
return True
direction = arr[1] - arr[0]
for i in range(2, len(arr)):
if direction == 0:
direction = arr[i] - arr[i - 1]
continue
if (direction > 0 and arr[i] < arr[i - 1]) or (direction < 0 and
arr[i] > arr[i - 1]):
return False
return True

# Example usage
arr1 = [1, 2, 3, 4, 5] # True
arr2 = [5, 4, 3, 2, 1] # True
arr3 = [1, 2, 2, 3, 4] # True
arr4 = [1, 2, 3, 4, 5, 4] # False

print(isMonotonic(arr1)) # should return True


print(isMonotonic(arr2)) # should return True
print(isMonotonic(arr3)) # should return True
print(isMonotonic(arr4)) # should return False

Output
True
True
True
False
This program first checks if the length of the array is less than or equal to 2, in which
case it returns True. Next, it initializes a variable “direction” to the difference between
the first two elements of the array. Then, it iterates through the rest of the array and
checks if the current element is greater than or less than the previous element,
depending on the direction. If any element does not match the direction, the function
returns False. If the function completes the loop and has not returned False, it returns
True.
Please note that this program assumes that the input array is a list of integers, if the
input array consists of other data types it will not work as expected.
The time complexity of the above program is O(n). This is because the program
iterates through the entire array once, and the amount of time it takes to complete the
iteration is directly proportional to the number of elements in the array. The program
uses a single variable “direction” to store the difference between the first two
elements of the array, and a single variable “i” to keep track of the current index
during iteration.
The auxiliary space of the above program is O(1). This is because the program only
uses a constant amount of extra memory to store the single variable “direction” and
the single variable “i”. The program does not create any new data structures or use
any recursion, so it does not require any additional memory beyond the input array.
Approach : By using the set to Identify Unique Elements
In this we will check, if the array is monotonic by converting it to a set to identify
unique elements and then determining monotonicity by comparing the array against
both its ascending and descending sorted versions. If either comparison holds true, the
array is considered monotonic.
Below is implementation for the above approach:
Python3
def is_monotonic(arr):
unique_elements = set(arr)
increasing = sorted(arr) == arr or sorted(arr, reverse=True) == arr
return increasing
# Driver Code
arr1 = [6, 5, 4, 4]
arr2 = [5, 15, 20, 10]
arr3 = [2, 2, 2, 3]

print(is_monotonic(arr1))
print(is_monotonic(arr2))
print(is_monotonic(arr3))

Output
True
False
True
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach : By using all and any Functions
In this approach, we are using all() function to check if the given array is monotonic
or not.
Python3
def is_monotonic(arr):
increasing = all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
decreasing = all(arr[i] >= arr[i + 1] for i in range(len(arr) - 1))

return increasing or decreasing

# Example
input_array1 = [6, 5, 4, 4]
input_array2 = [5, 15, 20, 10]
result1 = is_monotonic(input_array1)
result2 = is_monotonic(input_array2)
print(result1)
print(result2)

Output
True
False
Time complexity : O(n)
Auxiliary Space : O(1)
Python program to interchange first and last
elements in a list
Last Updated : 18 May, 2023



Given a list, write a Python program to swap first and last element of the list.
Examples:
Input : [12, 35, 9, 56, 24]
Output : [24, 35, 9, 56, 12]

Input : [1, 2, 3]
Output : [3, 2, 1]
Approach #1: Find the length of the list and simply swap the first element with (n-
1)th element.
 Python3

# Python3 program to swap first

# and last element of a list

# Swap function

def swapList(newList):

size = len(newList)

# Swapping

temp = newList[0]
newList[0] = newList[size - 1]

newList[size - 1] = temp

return newList

# Driver code

newList = [12, 35, 9, 56, 24]

print(swapList(newList))

Output
[24, 35, 9, 56, 12]
Approach #2: The last element of the list can be referred as list[-1]. Therefore, we
can simply swap list[0] with list[-1].
 Python3

# Python3 program to swap first

# and last element of a list

# Swap function
def swapList(newList):

newList[0], newList[-1] = newList[-1], newList[0]

return newList

# Driver code

newList = [12, 35, 9, 56, 24]

print(swapList(newList))

Output
[24, 35, 9, 56, 12]
Time Complexity: O(1)
Auxiliary Space: O(n), where n is length of list
Approach #3: Swap the first and last element is using tuple variable. Store the first
and last element as a pair in a tuple variable, say get, and unpack those elements with
first and last element in that list. Now, the First and last values in that list are
swapped.
 Python3

# Python3 program to swap first

# and last element of a list


# Swap function

def swapList(list):

# Storing the first and last element

# as a pair in a tuple variable get

get = list[-1], list[0]

# unpacking those elements

list[0], list[-1] = get

return list

# Driver code

newList = [12, 35, 9, 56, 24]

print(swapList(newList))

Output
[24, 35, 9, 56, 12]
Approach #4: Using * operand.
This operand proposes a change to iterable unpacking syntax, allowing to specify a
“catch-all” name which will be assigned a list of all items not assigned to a “regular”
name.
 Python3

# Python3 program to illustrate

# the usage of * operand

list = [1, 2, 3, 4]

a, *b, c = list

print(a)

print(b)

print(c)

Output
1
[2, 3]
4
Now let’s see the implementation of above approach:

 Python3

# Python3 program to swap first


# and last element of a list

# Swap function

def swapList(list):

start, *middle, end = list

list = [end, *middle, start]

return list

# Driver code

newList = [12, 35, 9, 56, 24]

print(swapList(newList))

Output
[24, 35, 9, 56, 12]
Approach #5: Swap the first and last elements is to use the inbuilt function list.pop().
Pop the first element and store it in a variable. Similarly, pop the last element and
store it in another variable. Now insert the two popped element at each other’s
original position.
 Python3
# Python3 program to swap first

# and last element of a list

# Swap function

def swapList(list):

first = list.pop(0)

last = list.pop(-1)

list.insert(0, last)

list.append(first)

return list

# Driver code

newList = [12, 35, 9, 56, 24]

print(swapList(newList))
Output
[24, 35, 9, 56, 12]

Approach #6: Using slicing

In this approach, we first check if the list has at least 2 elements.


If the list has at least 2 elements, we swap the first and last elements using slicing by
assigning the value of the last element to the first element and the value of the first
element to the last element.
We then slice the list from the second element to the second-to-last element and
concatenate it with a list containing the first element and the last element in their new
positions.

 Python3

def swap_first_last_3(lst):

# Check if list has at least 2 elements

if len(lst) >= 2:

# Swap the first and last elements using slicing

lst = lst[-1:] + lst[1:-1] + lst[:1]

return lst

# Initializing the input

inp=[12, 35, 9, 56, 24]

# Printing the original input


print("The original input is:",inp)

result=swap_first_last_3(inp)

# Printing the result

print("The output after swap first and last is:",result)

Output
The original input is: [12, 35, 9, 56, 24]
The output after swap first and last is: [24, 35, 9, 56, 12]

Python Program to Swap Two Elements in a


List
Last Updated : 03 Jul, 2023



Given a list in Python and provided the positions of the elements, write a program to
swap the two elements in the list.
Examples:
Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
Output : [19, 65, 23, 90]
Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5
Output : [1, 5, 3, 4, 2]
Swap Two Elements in a List using comma assignment
Since the positions of the elements are known, we can simply swap the positions of
the elements.
 Python3
# Python3 program to swap elements

# at given positions

# Swap function

def swapPositions(list, pos1, pos2):

list[pos1], list[pos2] = list[pos2], list[pos1]

return list

# Driver function

List = [23, 65, 19, 90]

pos1, pos2 = 1, 3

print(swapPositions(List, pos1-1, pos2-1))

Output:

[19, 65, 23, 90]


Time Complexity: O(1), for using constant operations.
Auxiliary Space: O(1), for using constant extra space.
Using Inbuilt list.pop() function to Swap Two Elements in a List
Pop the element at pos1 and store it in a variable. Similarly, pop the element
at pos2 and store it in another variable. Now insert the two popped element at each
other’s original position.
 Python3

# Python3 program to swap elements

# at given positions

# Swap function

def swapPositions(list, pos1, pos2):

# popping both the elements from list

first_ele = list.pop(pos1)

second_ele = list.pop(pos2-1)

# inserting in each others positions

list.insert(pos1, second_ele)

list.insert(pos2, first_ele)

return list

# Driver function
List = [23, 65, 19, 90]

pos1, pos2 = 1, 3

print(swapPositions(List, pos1-1, pos2-1))

Output:

[19, 65, 23, 90]


Time Complexity: O(1), for using constant operations.
Auxiliary Space: O(1), for using constant extra space.
Swap Two Elements in a List Using tuple variable
Store the element at pos1 and pos2 as a pair in a tuple variable, say get. Unpack those
elements with pos2 and pos1 positions in that list. Now, both the positions in that list
are swapped.
 Python3

# Python3 program to swap elements at

# given positions

# Swap function

def swapPositions(list, pos1, pos2):

# Storing the two elements

# as a pair in a tuple variable get


get = list[pos1], list[pos2]

# unpacking those elements

list[pos2], list[pos1] = get

return list

# Driver Code

List = [23, 65, 19, 90]

pos1, pos2 = 1, 3

print(swapPositions(List, pos1-1, pos2-1))

Output:

[19, 65, 23, 90]


Time Complexity: O(1), for using constant operations.
Auxiliary Space: O(1), for using constant extra space.
Swap Two Elements in a List Using temp variable
 Python3

# Python3 program to swap elements


# at given positions

# Swap function

def swapPositions(lis, pos1, pos2):

temp=lis[pos1]

lis[pos1]=lis[pos2]

lis[pos2]=temp

return lis

# Driver function

List = [23, 65, 19, 90]

pos1, pos2 = 1, 3

print(swapPositions(List, pos1-1, pos2-1))

Output
[19, 65, 23, 90]
Time Complexity: O(1), for using constant operations.
Auxiliary Space: O(1), for using constant extra space.
Swap Two Elements in a List Using enumerate
Another approach to swapping elements in a list is to use the enumerate function to
get the index and value of each element in the list, and then use a loop to find the
elements that need to be swapped and swap them.
 Python3
def swapPositions(lis, pos1, pos2):

for i, x in enumerate(lis):

if i == pos1:

elem1 = x

if i == pos2:

elem2 = x

lis[pos1] = elem2

lis[pos2] = elem1

return lis

List = [23, 65, 19, 90]

pos1, pos2 = 1, 3

print(swapPositions(List, pos1-1, pos2-1))

#This code is contributed by Edula Vinay Kumar Reddy

Output
[19, 65, 23, 90]
This approach has a time complexity of O(n), since it involves looping through the
entire list to find the elements to be swapped. The space complexity is O(1), since it
only uses a constant amount of additional space to store the elements to be swapped.
Note that this approach can be made more efficient by using a single loop and
breaking out of the loop once the elements have been found and swapped.
How To Find the Length of a List in Python
Last Updated : 21 Dec, 2023



List being an integral part of Python programming has to be learned by all Python
users and having a knowledge of its utility and operations is essential and always a
plus.
Many operations are performed in lists, but in this article, we will discuss the length
of a list. The length of a list means the number of elements it has. We are going to
look at 8 different methods to find the length of a list in Python.
Example:
Input: lst = [10,20,30,40]
Output: 4
Explanation: The output is 4 because the length of the list is 4.
Find the Length of a List in Python
Below are the methods that we will cover in this article:
 Using len() function
 Using Naive Method
 Using length_hint()
 Using sum() method
 Using a list comprehension
 Using recursion
 Using enumerate function
 Using Collections Module
1. Find the Length of a List Using len() Function
Python len() function is an inbuilt function in Python. It can be used to find the length
of an object by passing the object within the parentheses of the len function.
 Python3

# Python len()

li = [10, 20, 30]

n = len(li)

print("The length of list is: ", n)


Output:
The length of list is: 3
Time Complexity: O(n), where n is the length of the list
Auxiliary Space: O(1)
2. Find the Length of a List Using Naive Method
In this method, one just runs a loop and increases the counter till the last element of
the list to know its count. This is the most basic strategy that can be possibly
employed in the absence of other present techniques.
 Python3

# Initializing list

test_list = [1, 4, 5, 7, 8]

# Printing test_list

print("The list is : " + str(test_list))

# Finding length of list using loop

# Initializing counter

counter = 0

for i in test_list:

# incrementing counter

counter = counter + 1
# Printing length of list

print("Length of list using naive method is : " + str(counter))

Output:
The list is : [1, 4, 5, 7, 8]
Length of list using naive method is : 5
Time Complexity: O(n)
Auxiliary Space: O(1)
3. Find the Length of a List Using length_hint() Method
This technique is a lesser-known technique for finding list length. This particular
method is defined in the operator class and it can also tell the no. of elements present
in the list. Here, we are finding length of list using len() and length_hint()
 Python3

from operator import length_hint

# Initializing list

test_list = [1, 4, 5, 7, 8]

# Printing test_list

print("The list is : " + str(test_list))

# Finding length of list using len()


list_len = len(test_list)

# Finding length of list using length_hint()

list_len_hint = length_hint(test_list)

# Printing length of list

print("Length of list using len() is : " + str(list_len))

print("Length of list using length_hint() is : " + str(list_len_hint))

Output :
The list is : [1, 4, 5, 7, 8]
Length of list using len() is : 5
Length of list using length_hint() is : 5
4. Find the Length of a List Using sum() Function
Use iteration inside the sum and with each iteration adds one and at the end of the
iteration, we get the total length of the list.
 Python3

# Initializing list

test_list = [1, 4, 5, 7, 8]

# Printing test_list

print("The list is : " + str(test_list))


# Finding length of list

# using sum()

list_len = sum(1 for i in test_list)

# Printing length of list

print("Length of list using len() is : " + str(list_len))

print("Length of list using length_hint() is : " + str(list_len))

Output:
The list is : [1, 4, 5, 7, 8]
Length of list using len() is : 5
Length of list using length_hint() is : 5

5. Find the Length of a List Using a List Comprehension


Initialize a list called test_list with some values then Initialize a variable called length
to 0. Use a list comprehension to generate a sequence of ones for each element in the
test_list.
This will create a list of ones with the same length as the test_list. Now use the sum()
function to sum all the ones in the list generated by the list comprehension. Assign the
sum to the length variable. Print the length variable.
 Python3

# Define the list to be used for the demonstration


test_list = [1, 4, 5, 7, 8]

# Calculate the length of the list using a list comprehension and the sum function

# The list comprehension generates a sequence of ones for each element in the list

# The sum function then sums all the ones to give the length of the list

length = sum(1 for _ in test_list)

# Print the length of the list

print("Length of list using list comprehension is:", length)

Output
Length of list using list comprehension is: 5

Time Complexity: The list comprehension creates a new list with a length equal to
the length of the test_list. The sum() function then iterates over this list to compute the
sum. Therefore, the time complexity of this algorithm is O(N), where N is the length
of the test_list.
Auxiliary Space: The algorithm creates a new list of ones with a length equal to the
length of the test_list using the list comprehension. Therefore, the auxiliary space
complexity is also O(N), where N is the length of the test_list.
6. Find the Length of a List Using Recursion
We can use a recurcive function that takes a list lst as input and recursively calls itself,
passing in a slice of the list that excludes the first element until the list is empty.
The base case is when the list is empty, in which case the function returns 0.
Otherwise, it adds 1 to the result of calling the function on the rest of the list.
 Python3
# Define a function to count the number of elements in a list using recursion

def count_elements_recursion(lst):

# Base case: if the list is empty, return 0

if not lst:

return 0

# Recursive case: add 1 to the count of the remaining elements in the list

return 1 + count_elements_recursion(lst[1:])

# Test the function with a sample list

lst = [1, 2, 3, 4, 5]

print("The length of the list is:", count_elements_recursion(lst))

# Output: The length of the list is: 5

Output
The length of the list is: 5

Time complexity: O(n) where n is the length of the list. This is because the function
makes n recursive calls, each taking O(1) time, and there is also O(1) work done at
each level outside of the recursive call.
Space complexity: O(n) where n is the length of the list. This is because the function
creates n stack frames on the call stack due to the recursive calls.
7. Find the Length of a List Using enumerate() function
Python enumerate() method adds a counter to an iterable and returns it in a form of an
enumerating object.
 Python3

# python code to find the length

# of list using enumerate function

list1 = [1, 4, 5, 7, 8]

s =0

for i, a in enumerate(list1):

s += 1

print(s)

Output
5

8. Find the Length of a List Using Collections


Alternatively, you can also use the sum() function along with the values() method of
the Collections Counter object to get the length of the list.
 Python3

from collections import Counter


# Initializing list

test_list = [1, 4, 5, 7, 8]

# Finding length of list using Counter()

list_len = sum(Counter(test_list).values())

print("Length of list using Counter() is:", list_len)

# This code is contributed by Edula Vinay Kumar Reddy

Output
Length of list using Counter() is: 5

Time complexity: O(n), where n is the length of the list. This is because the
Counter() function has a time complexity of O(n) when applied to a list of length n,
and the values() method and the sum() function both have a time complexity of O(n)
when applied to a list of length n.
The space complexity: O(n), as the Counter() function, creates a dictionary with n
key-value pairs, each representing an element and its count in the list, respectively.
This dictionary takes up O(n) space.
Performance Analysis: Naive vs Python len() vs Python
length_hint()
When choosing amongst alternatives it’s always necessary to have a valid reason why
to choose one over another. This section does a time analysis of how much time it
takes to execute all of them to offer a better choice to use.
 Python3
from operator import length_hint

import time

# Initializing list

test_list = [1, 4, 5, 7, 8]

# Printing test_list

print("The list is : " + str(test_list))

# Finding length of list

# using loop

# Initializing counter

start_time_naive = time.time()

counter = 0

for i in test_list:

# incrementing counter

counter = counter + 1
end_time_naive = str(time.time() - start_time_naive)

# Finding length of list

# using len()

start_time_len = time.time()

list_len = len(test_list)

end_time_len = str(time.time() - start_time_len)

# Finding length of list

# using length_hint()

start_time_hint = time.time()

list_len_hint = length_hint(test_list)

end_time_hint = str(time.time() - start_time_hint)

# Printing Times of each

print("Time taken using naive method is : " + end_time_naive)

print("Time taken using len() is : " + end_time_len)

print("Time taken using length_hint() is : " + end_time_hint)

Output:
The list is : [1, 4, 5, 7, 8]
Time taken using naive method is : 2.6226043701171875e-06
Time taken using len() is : 1.1920928955078125e-06
Time taken using length_hint() is : 1.430511474609375e-06

In the below images, it can be clearly seen that time taken is naive >> length_hint() >
len(), but the time taken depends highly on the OS and several of its parameter.
In two consecutive runs, you may get contrasting results, in fact sometimes naive
takes the least time out of three. All the possible 6 permutations are possible.

naive > len() > length_hint()

naive > len()=length_hint()

naive > length_hint() >len()

naive > length_hint() > len()

We have discussed 8 different methods to find the length of a list in Python. We have
also done a performance analysis to check which method is the best.
You can use any of the above methods to find the length of a list. Finding list length is
very useful when dealing with huge lists and you want to check the number of entries.
Check if element exists in list in Python
Last Updated : 26 Mar, 2024



The list is an important container in Python as it stores elements of all the data types
as a collection. Knowledge of certain list operations is necessary for day-day
programming. This article discusses the Fastest way to check if a value exists in a list
or not using Python.
Example
Input: test_list = [1, 6, 3, 5, 3, 4]
3 # Check if 3 exist or not.
Output: True
Explanation: The output is True because the element we are looking is
exist in the list.
Check if an element exists in a list in Python
 Using “in” Statement
 Using a loop
 Using any() function
 Using count() function
 Using sort with bisect_left and set()
 Using find() method
 Using Counter() function
 Using try-except block
Check if an element exists in the list using the “in” statement
In this method, one easily uses a loop that iterates through all the elements to check
the existence of the target element. This is the simplest way to check the existence of
the element in the list. Python is the most conventional way to check if an element
exists in a list or not. This particular way returns True if an element exists in the list
and False if the element does not exist in the list. The list need not be sorted to
practice this approach of checking.
Python3
lst=[ 1, 6, 3, 5, 3, 4 ]
#checking if element 7 is present
# in the given list or not
i=7
# if element present then return
# exist otherwise not exist
if i in lst:
print("exist")
else:
print("not exist")

Output
not exist

Time Complexity: O(1)


Auxiliary Space: O(n), where n is the total number of elements.
Find if an element exists in the list using a loop
The given Python code initializes a list named test_list with some integer elements.
It then iterates through each element in the list using a for loop. Inside the loop, it
checks if the current element i is equal to the value 4 using an if statement. If the
condition is true, it prints “Element Exists” to the console. The code will output the
message if the number 4 is present in the list, and in this case, “Element Exists” will
be printed since the number 4 exists in the list [1, 6, 3, 5, 3, 4].
Python3
# Initializing list
test_list = [1, 6, 3, 5, 3, 4]

# Checking if 4 exists in list


for i in test_list:
if(i == 4):
print("Element Exists")
Output:
Element Exists
Time Complexity: O(n)
Auxiliary Space: O(1)
Check if an element exists in the list using any() function
It achieves this by utilizing the any() function with a generator expression. The
generator expression iterates through each element test_list and checks if it appears
more than once in the list. The result of this check is stored in the variable result.
Finally, the code prints a message indicating whether there are any duplicate elements,
displaying “Does string contain any list element: True” if duplicates exist and “Does
string contain any list element: False” if there are no duplicates.
Python3
# Initializing list
test_list = [1, 6, 3, 5, 3, 4]

result = any(item in test_list for item in test_list)


print("Does string contain any list element : " +str(bool(result)))
Output:
Does string contain any list element : True
Find if an element exists in the list using the count() function
We can use the in-built Python List method, count(), to check if the passed element
exists in the List. If the passed element exists in the List, the count() method will show
the number of times it occurs in the entire list. If it is a non-zero positive number, it
means an element exists in the List. Demonstrating to check the existence of elements
in the list using count().
Python3
# Initializing list
test_list = [10, 15, 20, 7, 46, 2808]

print("Checking if 15 exists in list")

# number of times element exists in list


exist_count = test_list.count(15)

# checking if it is more than 0


if exist_count > 0:
print("Yes, 15 exists in list")
else:
print("No, 15 does not exists in list")
Output:
Checking if 15 exists in list
Yes, 15 exists in list
Check if an element exists in the list using sort with bisect_left and set
Converting the list into the set and then using it can possibly be more efficient than
only using it. But having efficiency as a plus also has certain negatives. One among
them is that the order of the list is not preserved, and if you opt to take a new list for
it, you would require to use extra space. Another drawback is that set disallows
duplicity and hence duplicate elements would be removed from the original list. In the
conventional binary search way of testing element existence, hence list has to be
sorted first and hence does not preserve the element ordering. bisect_left() returns the
first occurrence of the element to be found and has worked similarly
to lower_bound() in C++ STL.
Note: The bisect function will only state the position of where to insert the element but
not the details about if the element is present or not.
Demonstrating to check existence of element in list using set() + in
and sort() + bisect_left()
Python3
from bisect import bisect_left ,bisect

# Initializing list
test_list_set = [ 1, 6, 3, 5, 3, 4 ]
test_list_bisect = [ 1, 6, 3, 5, 3, 4 ]

print("Checking if 4 exists in list ( using set() + in) : ")

# Checking if 4 exists in list


# using set() + in
test_list_set = set(test_list_set)
if 4 in test_list_set :
print ("Element Exists")

print("Checking if 4 exists in list ( using sort() + bisect_left() ) : ")

# Checking if 4 exists in list


# using sort() + bisect_left()
test_list_bisect.sort()
if bisect_left(test_list_bisect, 4)!=bisect(test_list_bisect, 4):
print ("Element Exists")
else:
print("Element doesnt exist")
Output:
Checking if 4 exists in list ( using set() + in) :
Element Exists
Checking if 4 exists in list ( using sort() + bisect_left() ) :
Element Exists
Check if an element exists in list using find() method
The given Python code checks if the number 15 exists in the list test_list. It
converts the elements of the list to strings and concatenates them with hyphens. Then,
it uses the find() method to check if the substring “15” exists in the resulting string.
If “15” is found, it prints “Yes, 15 exists in the list”; otherwise, it prints “No, 15 does
not exist in the list.”
Python3
# Initializing list
test_list = [10, 15, 20, 7, 46, 2808]

print("Checking if 15 exists in list")


x=list(map(str,test_list))
y="-".join(x)

if y.find("15") !=-1:
print("Yes, 15 exists in list")
else:
print("No, 15 does not exists in list")

Output
Checking if 15 exists in list
Yes, 15 exists in list

Check if element exists in list using Counter() function


The provided Python code uses the Counter class from the collections module to
calculate the frequency of each element in the test_list. It then checks if the
frequency of the number 15 is greater than 0. If the frequency is non-zero, it means
“15” exists in the list, and the code prints “Yes, 15 exists in the list.” Otherwise, it
prints “No, 15 does not exist in the list.” The Counter class efficiently counts element
occurrences, allowing for a straightforward existence check.
Python3
from collections import Counter

test_list = [10, 15, 20, 7, 46, 2808]

# Calculating frequencies
frequency = Counter(test_list)

# If the element has frequency greater than 0


# then it exists else it doesn't exist
if(frequency[15] > 0):
print("Yes, 15 exists in list")
else:
print("No, 15 does not exists in list")

Output
Yes, 15 exists in list
Find if an an element exists in list using try-except block
One additional approach to check if an element exists in a list is to use
the index() method. This method returns the index of the first occurrence of the
element in the list or throws a ValueError if the element is not present in the list. To
use this method, you can wrap the call to index() in a try-except block to catch the
ValueError and return False if it occurs:
Python3
def element_exists(lst, element):
# Try to get the index of the element in the list
try:
lst.index(element)
# If the element is found, return True
return True
# If a ValueError is raised, the element is not in the list
except ValueError:
# Return False in this case
return False

#Test the function


test_list = [1, 6, 3, 5, 3, 4]

print(element_exists(test_list, 3)) # prints True


print(element_exists(test_list, 7)) # prints False
#This code is contributed by Edula Vinay Kumar Reddy

Output
True
False

Time complexity: O(n), where n is the length of the list. The index() method iterates
through the list to find the element, so the time complexity is linear.
Space complexity: O(1). This approach does not require any additional space.
Find if an an element exists in list using filter() Function
Step-by-Step Approach
 Define the list my_list and Set element_to_check.
 Use the filter() function to create an iterator (filtered_elements) that contains
elements equal to the element_to_check.
 Convert the iterator filtered_elements to a list.
 This step is necessary as the filter() function returns an iterator. The list now
contains elements equal to element_to_check.
 Check if the list filtered_list is not empty.
 If the list is not empty, it means the element exists in the original list.
Python
my_list = [1, 2, 3, 4, 5]
element_to_check = 3

# Use filter to create an iterator of elements equal to the target element


filtered_elements = filter(lambda x: x == element_to_check, my_list)

# Convert the iterator to a list and check if it's not empty


if list(filtered_elements):
print("Element exists in the list")
else:
print("Element does not exist in the list")

Output
Element exists in the list
Time Complexity: O(n)
Auxiliary Space Complexity: O(n)
Different ways to clear a list in Python
Last Updated : 26 Mar, 2024



In this article, let’s discuss different ways to clear a list in Python. Python provides a
lot of different ways to clear a list and we will discuss them in this article.
Example
Input: [2, 3, 5, 6, 7]
Output: []
Explanation: Python list is cleared and it becomes empty so we have
returned empty list.
Different Ways to Remove from a List in Python
There are many ways of clearing the list through methods of different constructs
offered by Python language. Let’s try to understand each of the methods one by one.
 Using clear()
 Reinitializing the list
 Using “*= 0”
 Using del
 Using pop() method
 Using slicing
 using list comprehension
Clear a List using Python List clear()
In this example, we are using clear() method to clear a list in Python.
Python3
GEEK = [6, 0, 4, 1]
print('GEEK before clear:', GEEK)

# Clearing list
GEEK.clear()
print('GEEK after clear:', GEEK)

Output
GEEK before clear: [6, 0, 4, 1]
GEEK after clear: []

Clear a List by Reinitializing the List


The initialization of the list in that scope initializes the list with no value. i.e list of
size 0. Let’s see the example demonstrating Method 1 and 2 to clear list.
Python3
list1 = [1, 2, 3]

# Printing list2 before deleting


print("List1 before deleting is : "
+ str(list1))

# deleting list using reinitialization


list1 = []

# Printing list2 after reinitialization


print("List1 after clearing using reinitialization : "
+ str(list1))

Output
List1 before deleting is : [1, 2, 3]
List1 after clearing using reinitialization : []

Clearing a Python List Using “*= 0”


This is a lesser-known method, but this method removes all elements of the list and
makes it empty. In this example, we are using *=0 to clear a list.
Python3
# Initializing lists
list1 = [1, 2, 3]

# Printing list2 before deleting


print("List1 before clearing is : "
+ str(list1))

list1*=0
# Printing list2 after reinitialization
print("List1 after clearing using *=0 : "
+ str(list1))

Output
List1 before clearing is : [1, 2, 3]
List1 after clearing using *=0 : []

Clearing a List Using del


Python del can be used to clear the list elements in a range, if we don’t give a range,
all the elements are deleted. In this example, we are using del keyword to clear a list.
Python3
list1 = [1, 2, 3]
list2 = [5, 6, 7]

# Printing list1 before deleting


print("List1 before deleting is : " + str(list1))

# deleting list1 using del


del list1[:]
print("List1 after clearing using del : " + str(list1))

# Printing list2 before deleting


print("List2 before deleting is : " + str(list2))

# deleting list using del


del list2[:]
print("List2 after clearing using del : " + str(list2))

Output
List1 before deleting is : [1, 2, 3]
List1 after clearing using del : []
List2 before deleting is : [5, 6, 7]
List2 after clearing using del : []

Python pop() method To Clear a List


In this example, we are using pop() method to clear a list.
Python3
list1 = [1, 2, 3]

# Printing list1 before deleting


print("List1 before deleting is : " + str(list1))

# deleting list1
while(len(list1) != 0):
list1.pop()
print("List1 after clearing using del : " + str(list1))

Output
List1 before deleting is : [1, 2, 3]
List1 after clearing using del : []

Time Complexity: O(n^2) where n is the length of the list list1.


Auxiliary Space: O(1).
Clear a List using Slicing
This method involves using slicing to create a new list with no elements, and then
assigning it to the original list variable. In this example, we are using slicing to clear a
list.
Python3
# Initializing list
lst = [1, 2, 3, 4, 5]

print("List before clearing: ",lst)


# Clearing list using slicing
lst = lst[:0]
print("List after clearing using Slicing: ",lst)

Output
List before clearing: [1, 2, 3, 4, 5]
List after clearing using Slicing: []

Time Complexity: O(1)


Auxiliary Space: O(n), where n is length of list.
Clear a list using list comprehension method
The clear_list function is designed to clear or empty the input list, lst, by
comprehensively filtering its elements through a list comprehension that always
evaluates to False. Here’s a simplified explanation based on your example:
1. Function Definition: clear_list(lst) takes a list lst as its parameter.
2. List Comprehension: Inside the function, a new list is created with a list
comprehension [item for item in lst if False]. Because the condition is
always False, no elements from the original list lst satisfy the condition,
resulting in an empty list.
3. Return Empty List: The function returns this newly created empty list.
4. Testing the Function: input_list is defined with elements [2, 3, 5, 6, 7].
When clear_list is called with input_list, it returns an empty list [].
5. Print Output: The output, which is an empty list, is printed, showing [].
Python
def clear_list(lst):
lst = [item for item in lst if False]
return lst

input_list = [2, 3, 5, 6, 7]
output = clear_list(input_list)
print(output) # Output: []

Output
[]
Time complexity:O(n)
auxiliary space:O(n), where n is length of list. Reversing a List
in Python
Last Updated : 04 Dec, 2023



Python provides us with various ways of reversing a list. We will go through some of
the many techniques on how a list in Python can be reversed.
Example:
Input: list = [4, 5, 6, 7, 8, 9]
Output: [9, 8, 7, 6, 5, 4]
Explanation: The list we are having in the output is reversed to the
list we have in the input.

Reversing a List in Python


Below are the approaches that we will cover in this article:
 Using the slicing technique
 Reversing list by swapping present and last numbers at a time
 Using the reversed() and reverse() built-in function
 Using a two-pointer approach
 Using the insert() function
 Using list comprehension
 Reversing a list using Numpy
1. Reverse List Using Slicing Technique
In this technique, a copy of the list is made, and the list is not sorted in place. Creating
a copy requires more space to hold all the existing elements. This exhausts more
memory. Here we are using the slicing technique to reverse our list in Python.
 Python3

# Reversing a list using slicing technique


def Reverse(lst):

new_lst = lst[::-1]

return new_lst

lst = [10, 11, 12, 13, 14, 15]

print(Reverse(lst))

Output
[15, 14, 13, 12, 11, 10]

Time complexity: O(n)


Auxiliary space: O(n)
2. Reverse List by Swapping Present and Last Numbers at a Time
Here is the approach:
If the arr[], size if the length of the array is 1, then return arr. elif length of the array is
2, swap the first and last number and return arr. otherwise, initialize i=0. Loop for i in
size//2 then swap the first present and last present numbers if the first and next
numbers indexes are not same, then swap next and last of next numbers then
increment i+=2, and after looping return arr.
 Python3
#Python program to reverse an array

def list_reverse(arr,size):

#if only one element present, then return the array

if(size==1):

return arr

#if only two elements present, then swap both the numbers.

elif(size==2):

arr[0],arr[1],=arr[1],arr[0]

return arr

#if more than two elements presents, then swap first and last numbers.

else:

i=0

while(i<size//2):

#swap present and preceding numbers at time and jump to second element after swap
arr[i],arr[size-i-1]=arr[size-i-1],arr[i]

#skip if present and preceding numbers indexes are same

if((i!=i+1 and size-i-1 != size-i-2) and (i!=size-i-2 and size-i-1!=i+1)):

arr[i+1],arr[size-i-2]=arr[size-i-2],arr[i+1]

i+=2

return arr

arr=[1,2,3,4,5]

size=5

print('Original list: ',arr)

print("Reversed list: ",list_reverse(arr,size))

#This contributed by SR.Dhanush

Output
Original list: [1, 2, 3, 4, 5]
Reversed list: [5, 4, 3, 2, 1]
Time Complexity: O(log2(n)), where n is the length of the given array.
Auxiliary Space: O(1)
3. Reverse List Using the Reversed() and Reverse() Built-In Function
Using reversed() we can reverse the list and a list_reverseiterator object is created,
from which we can create a list using list() type casting. Or, we can also use the
list reverse() function to reverse list in place.
 Python3

lst = [10, 11, 12, 13, 14, 15]

lst.reverse()

print("Using reverse() ", lst)

print("Using reversed() ", list(reversed(lst)))

Output
Using reverse() [15, 14, 13, 12, 11, 10]
Using reversed() [10, 11, 12, 13, 14, 15]

Time complexity: O(n), where n is the length of the list lst.


Auxiliary space: O(1) since it modifies the original list in place and does not create a
new list.
4. Reverse a List Using a Two-Pointer Approach
In this method, we will declare two pointers(basically the start index and the end
index, let ‘left’ and ‘right’). While scanning the list, in each iteration we will swap the
elements at index ‘left’ and ‘right’.
The ‘left’ pointer will move forward and the ‘right’ pointer will move backward. We
will continue the process till ‘first’ < ‘last’. This will work for both an even number of
elements as well an odd number of elements.
 Python3
# Reversing a list using two-pointer approach

def reverse_list(arr):

left = 0

right = len(arr)-1

while (left < right):

# Swap

temp = arr[left]

arr[left] = arr[right]

arr[right] = temp

left += 1

right -= 1

return arr

arr = [1, 2, 3, 4, 5, 6, 7]

print(reverse_list(arr))

Output
[7, 6, 5, 4, 3, 2, 1]
Time Complexity: O(N)
Auxiliary Space: O(1)
5. Reverse a List Using the insert() Function
In this method, we neither reverse a list in place (modify the original list) nor create
any copy of the list. Instead, we keep inserting items at the 0th index of the list, this
will automatically reverse the list.
 Python3

# input list

lst = [10, 11, 12, 13, 14, 15]

# the above input can also be given as

# lst=list(map(int,input().split()))

l = [] # empty list

# iterate to reverse the list

for i in lst:

# reversing the list

l.insert(0, i)

# printing result

print(l)

Output
[15, 14, 13, 12, 11, 10]
Time complexity: O(n)
Auxiliary Space: O(n), where n is the length of the list.
6. Reverse a List Using List Comprehension
In this technique, the list is not sorted in place. A copy of the original array is not
required. We use list comprehension to reverse the array and return the list.
We find the length of the array and then iterate over it using the range. Now, to
replace the last element with the first, we subtract the length of the original list from
the index of the iterator.
 Python3

original_list = [10, 11, 12, 13, 14, 15]

new_list = [original_list[len(original_list) - i]

for i in range(1, len(original_list)+1)]

print(new_list)

Output
[15, 14, 13, 12, 11, 10]

Time complexity: O(n), where n is the length of the original_list.


Auxiliary space: O(n),
7. Reverse a List Using Numpy
Here we are going to use numpy package:
Initialize the input list my_listConvert my_list to a 1D numpy array using
np.array(my_list)Reverse the order of the array using my_array[::-1]Convert the
reversed numpy array back to a list using .tolist()
Print the reversed list
 Python3

import numpy as np

# Input list

my_list = [4, 5, 6, 7, 8, 9]

# Convert the list to a 1D numpy array

my_array = np.array(my_list)

# Reverse the order of the array

reversed_array = my_array[::-1]

# Convert the reversed array to a list

reversed_list = reversed_array.tolist()

# Print the reversed list

print(reversed_list)

Output:
[9, 8, 7, 6, 5, 4]
Time complexity: O(n)
Auxiliary space: O(n)
We have discussed many ways of reversing a list in Python. We have also mentioned
their time complexities and Auxiiary space to give you right idea about their
processing speed.
Hope this article helped you to understand ways on “how to reverse a python list?”
and you will easily reverse a list in Python.
Adding and Subtracting Matrices in Python
Last Updated : 25 Apr, 2023



In this article, we will discuss how to add and subtract elements of the matrix in
Python.
Example:
Suppose we have two matrices A and B.
A = [[1,2],[3,4]]
B = [[4,5],[6,7]]

then we get
A+B = [[5,7],[9,11]]
A-B = [[-3,-3],[-3,-3]]
Now let us try to implement this using Python
1. Adding elements of the matrix
In the above code, we have used np.add() method to add elements of two matrices. If
shape of two arrays are not same, that is arr1.shape != arr2.shape, they must be
broadcastable to a common shape (which may be the shape of one or the other).
 Python3

# importing numpy as np

import numpy as np
# creating first matrix

A = np.array([[1, 2], [3, 4]])

# creating second matrix

B = np.array([[4, 5], [6, 7]])

print("Printing elements of first matrix")

print(A)

print("Printing elements of second matrix")

print(B)

# adding two matrix

print("Addition of two matrix")

print(np.add(A, B))

Output:
Printing elements of first matrix
[[1 2]
[3 4]]
Printing elements of second matrix
[[4 5]
[6 7]]
Addition of two matrix
[[ 5 7]
[ 9 11]]
2. Subtracting elements of matrices
In the above code, we have used np.subtract() to subtract elements of two matrices. It
returns the difference of arr1 and arr2, element-wise.
 Python3

# importing numpy as np

import numpy as np

# creating first matrix

A = np.array([[1, 2], [3, 4]])

# creating second matrix

B = np.array([[4, 5], [6, 7]])

print("Printing elements of first matrix")

print(A)

print("Printing elements of second matrix")


print(B)

# subtracting two matrix

print("Subtraction of two matrix")

print(np.subtract(A, B))

Output:
Printing elements of first matrix
[[1 2]
[3 4]]
Printing elements of second matrix
[[4 5]
[6 7]]
Subtraction of two matrix
[[-3 -3]
[-3 -3]]
METHOD 3:Using nested loops
APPROACH:
The given task is to subtract two matrices in Python and print their elements.
Approach 2 uses nested loops to subtract the two matrices. It prints the elements of
both matrices using nested loops and then subtracts the corresponding elements of the
matrices to get the result matrix.
ALGORITHM:
1. Define two matrices matrix1 and matrix2.
2.Print the elements of matrix1 and matrix2 using nested loops.
3. Define an empty matrix result of the same size as matrix1.
4. Subtract the corresponding elements of matrix1 and matrix2 using nested loops and
store the result in the result matrix.
5. Print the result matrix.

 Python3
# Input matrices

matrix1 = [[1, 2], [3, 4]]

matrix2 = [[4, 5], [6, 7]]

# Printing elements of matrix1

print("Printing elements of first matrix")

for row in matrix1:

for element in row:

print(element, end=" ")

print()

# Printing elements of matrix2

print("Printing elements of second matrix")

for row in matrix2:

for element in row:

print(element, end=" ")

print()

# Subtracting two matrices


result = [[0, 0], [0, 0]]

for i in range(len(matrix1)):

for j in range(len(matrix1[0])):

result[i][j] = matrix1[i][j] - matrix2[i][j]

# Printing the result

print("Subtraction of two matrix")

for row in result:

for element in row:

print(element, end=" ")

print()

Output
Printing elements of first matrix
1 2
3 4
Printing elements of second matrix
4 5
6 7
Subtraction of two matrix
-3 -3
-3 -3
Time complexity:
1. The time complexity of printing the matrices using nested loops is O(n^2), where n
is the size of the matrices.
2. The time complexity of subtracting two matrices using nested loops is also O(n^2).
3. Therefore, the overall time complexity of this approach is O(n^2).

Space complexity:
1.The space complexity of this approach is O(n^2), as it requires three matrices of size
n^2. The input matrices matrix1 and matrix2 require a space of n^2 each, and the
result matrix requires a space of n^2.

Python Program to Add Two Matrices


Last Updated : 24 Jun, 2023



Given two matrices X and Y, the task is to compute the sum of two matrices and then
print it in Python.
Examples:
Input :
X= [[1,2,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[9,8,7],
[6,5,4],
[3,2,1]]

Output :
result= [[10,10,10],
[10,10,10],
[10,10,10]]
Add Two Matrices Using for loop
Here we will use for loop with two matrices for adding the elements
 Python

# Program to add two matrices using nested loop


X = [[1,2,3],

[4 ,5,6],

[7 ,8,9]]

Y = [[9,8,7],

[6,5,4],

[3,2,1]]

result = [[0,0,0],

[0,0,0],

[0,0,0]]

# iterate through rows

for i in range(len(X)):

# iterate through columns

for j in range(len(X[0])):

result[i][j] = X[i][j] + Y[i][j]


for r in result:

print(r)

Learn Data Structures & Algorithms with GeeksforGeeks

Output
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Time Complexity: O(len(X) * len(X[0])), as we are using nested loop for traversing
the matrix.
Auxiliary Space: O(len(X) * len(X[0])), as we are using a result matrix which is
extra space.

Add Two Matrices Using List comprehension

In this program we have used nested for loops to iterate through each row and each
column. At each point we add the corresponding elements in the two matrices and
store it in the result.
Using nested list comprehension : In Python, we can implement a matrix as nested
list (list inside a list). We can treat each element as a row of the matrix.
Below is the implementation:

 Python

# Program to add two matrices

# using list comprehension


X = [[1,2,3],

[4 ,5,6],

[7 ,8,9]]

Y = [[9,8,7],

[6,5,4],

[3,2,1]]

result = [[X[i][j] + Y[i][j] for j in range

(len(X[0]))] for i in range(len(X))]

for r in result:

print(r)

Learn Data Structures & Algorithms with GeeksforGeeks

Output
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Time Complexity: O(len(X) * len(X[0])), as we are using nested loop for traversing
the matrix.
Auxiliary Space: O(len(X) * len(X[0])), as we are using a result matrix which is
extra space.
Add Two Matrices Using zip() function
The output of this program is the same as above. We have used nested list
comprehension to iterate through each element in the matrix. List comprehension
allows us to write concise codes and we must try to use them frequently in Python.
They are very helpful.
Below is the implementation:

 Python

# Program to add two matrices

# using zip()

X = [[1,2,3],

[4 ,5,6],

[7 ,8,9]]

Y = [[9,8,7],

[6,5,4],

[3,2,1]]

result = [map(sum, zip(*t)) for t in zip(X, Y)]

print(result)
Learn Data Structures & Algorithms with GeeksforGeeks

Output
[[10, 10, 10], [10, 10, 10], [10, 10, 10]]
Time Complexity: O(len(X) * len(X[0])), as we are using zip function.
Auxiliary Space: O(len(X) * len(X[0])), as we are using extra space.
Explanation:- The zip function accepts iterator i of each element(list) of matrix,
mapping them, adding them using sum(), and storing them in the map form.
Add Two Matrices Using Numpy
The numpy library has a built-in overload of the operator +, that allows one to
perform the addition of matrices.
Below is the implementation:

 Python3

# Program to add two matrices

# using numpy

import numpy as np

X = [[1,2,3],

[4 ,5,6],

[7 ,8,9]]

Y = [[9,8,7],

[6,5,4],
[3,2,1]]

result = np.array(X) + np.array(Y)

print(result)

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
[[10 10 10]
[10 10 10]
[10 10 10]]
Time Complexity: O(len(X) * len(X[0]))
Auxiliary Space: O(len(X) * len(X[0]))

Add Two Matrices Using SymPy

To add matrices using a library, you can use the Matrix class provided in the SymPy
library.
Here’s an example of how to use it:

 Python3

from sympy import Matrix

X = [[1, 2, 3],
[4, 5, 6],

[7, 8, 9]]

Y = [[9, 8, 7],

[6, 5, 4],

[3, 2, 1]]

# Create Matrix objects from the lists

matrix_x = Matrix(X)

matrix_y = Matrix(Y)

# Add the matrices

result = matrix_x + matrix_y

# Print the result

print(result)

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
Matrix([
[10, 10, 10],
[10, 10, 10],
[10, 10, 10]])

Python program to multiply two matrices


Last Updated : 28 Jul, 2023



Given two matrix the task is that we will have to create a program to multiply two
matrices in python.
Examples:
Input : X = [[1, 7, 3],
[3, 5, 6],
[6, 8, 9]]
Y = [[1, 1, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]

Output : [55, 65, 49, 5]


[57, 68, 72, 12]
[90, 107, 111, 21]
Recommended: Please try your approach on {IDE} first, before moving on to the
solution.
Using Simple Nested Loops: In this program we have to use nested for loops to
iterate through each row and each column.
Implementation:
fdfxfxddx
Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.
Method 2: Matrix Multiplication Using Nested List. We use zip in Python.
Implementation:
 Python3

# Program to multiply two matrices using list comprehension

# take a 3x3 matrix

A = [[12, 7, 3],

[4, 5, 6],

[7, 8, 9]]

# take a 3x4 matrix

B = [[5, 8, 1, 2],

[6, 7, 3, 0],

[4, 5, 9, 1]]

# result will be 3x4

result = [[sum(a * b for a, b in zip(A_row, B_col))

for B_col in zip(*B)]

for A_row in A]
for r in result:

print(r)

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.
Method 3: Matrix Multiplication (Vectorized implementation).
Implementation:
 Python3

# Program to multiply two matrices (vectorized implementation)

# Program to multiply two matrices (vectorized implementation)

import numpy as np

# take a 3x3 matrix

A = [[12, 7, 3],

[4, 5, 6],

[7, 8, 9]]

# take a 3x4 matrix


B = [[5, 8, 1, 2],

[6, 7, 3, 0],

[4, 5, 9, 1]]

# result will be 3x4

result= [[0,0,0,0],

[0,0,0,0],

[0,0,0,0]]

result = np.dot(A,B)

for r in result:

print(r)

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.
Method 4:Using recursive matrix multiplication:
Algorithm:
1. Check if the dimensions of the two input matrices are valid for multiplication. If
the number of columns in the first matrix does not equal the number of rows in the
second matrix, then they cannot be multiplied. In this case, raise an error or return
a None object.
2. Check if the matrices are of size 1×1. If they are, multiply their elements and
return the result.
3. If the matrices are not of size 1×1, divide each matrix into four submatrices of
equal size.
4. Recursively multiply the submatrices using the same algorithm, until each
submatrix is of size 1×1.
5. Compute the product of the resulting submatrices using the formula:
6. result = [A11B11 + A12B21, A11B12 + A12B22, A21B11 + A22B21, A21B12 +
A22B22]
7. Return the resulting matrix.
 Python3

def matrix_multiply_recursive(A, B):

# check if matrices can be multiplied

if len(A[0]) != len(B):

raise ValueError("Invalid matrix dimensions")

# initialize result matrix with zeros

result = [[0 for j in range(len(B[0]))] for i in range(len(A))]

# recursive multiplication of matrices

def multiply(A, B, result, i, j, k):

if i >= len(A):
return

if j >= len(B[0]):

return multiply(A, B, result, i+1, 0, 0)

if k >= len(B):

return multiply(A, B, result, i, j+1, 0)

result[i][j] += A[i][k] * B[k][j]

multiply(A, B, result, i, j, k+1)

# perform matrix multiplication

multiply(A, B, result, 0, 0, 0)

return result

# example usage

A = [[12, 7, 3], [4, 5, 6], [7, 8, 9]]

B = [[5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]]

result = matrix_multiply_recursive(A, B)

for row in result:


print(row)

Learn Data Structures & Algorithms with GeeksforGeeks

Output
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Time complexity: O(n^3)
Auxiliary Space : O(n^2)
Python | Matrix Product
Last Updated : 23 Apr, 2023



Getting the product of list is quite common problem and has been dealt with and
discussed many times, but sometimes, we require to better it and total product, i.e.
including those of nested list as well. Let’s try and get the total product and solve this
particular problem.
Method #1: Using list comprehension + loop
We can solve this problem using the list comprehension as a potential shorthand to the
conventional loops that we may use to perform this particular task. We just iterate and
product the nested list and at end return the cumulative product using function.

 Python3

# Python3 code to demonstrate

# Matrix Product

# Using list comprehension + loop


# getting Product

def prod(val):

res = 1

for ele in val:

res *= ele

return res

# initializing list

test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]

# printing original list

print("The original list : " + str(test_list))

# using list comprehension + loop

# Matrix Product
res = prod([ele for sub in test_list for ele in sub])

# print result

print("The total element product in lists is : " + str(res))

Output
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880
Time Complexity: O(N*M)
Auxiliary Space: O(1)
Method #2: Using chain() + loop
This particular problem can also be solved using the chain function instead of list
comprehension in which we use the conventional function to perform product.

 Python3

# Python3 code to demonstrate

# Matrix Product

# Using chain() + loop

from itertools import chain

# getting Product
def prod(val):

res = 1

for ele in val:

res *= ele

return res

# initializing list

test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]

# printing original list

print("The original list : " + str(test_list))

# using chain() + loop

# Matrix Product

res = prod(list(chain(*test_list)))

# print result

print("The total element product in lists is : " + str(res))

Output
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880
Time Complexity: O(N)
Auxiliary Space: O(1)
Method #3 : Using extend() method
 Python3

# Python3 code to demonstrate

# Matrix Product

# initializing list

test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]

# printing original list

print("The original list : " + str(test_list))

x = []

for i in test_list:

x.extend(i)

res = 1

for j in x:

res *= j
# print result

print("The total element product in lists is : " + str(res))

Output
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #4 : Using extend(), functools.reduce() and operator.mul
 Python3

# Python3 code to demonstrate

# Matrix Product

# initializing list

import operator

from functools import reduce

test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]

# printing original list


print("The original list : " + str(test_list))

x = []

for i in test_list:

x.extend(i)

res = reduce(operator.mul, x, 1)

# print result

print("The total element product in lists is : " + str(res))

Output
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #5:Using Nested Loops
This is the naive approach to solve the problem

 Python3

# Python3 code to demonstrate

# Matrix Product
# initializing list

test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]

# printing original list

print("The original list : " + str(test_list))

res = 1

for i in test_list:

for j in i:

res *= j

# print result

print("The total element product in lists is : " + str(res))

Output
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880
Time Complexity: O(N*M)
Auxiliary Space: O(1), Where N is the number of rows and M is the number of
columns
Method 6 : use recursion to traverse the nested list and multiply all the
elements.
 Define a function multiply_nested_list that takes a nested list as an argument.
 Initialize a variable res with the value 1.
 Iterate over each element i in the input list using a for loop.
 Check if the current element i is a list or not, using the isinstance() function.
 If the current element i is a list, call the multiply_nested_list() function recursively
with i as an argument, and multiply the result with the res variable.
 If the current element i is not a list, multiply the res variable with i.
 Return the final result stored in the res variable.
 Initialize a test list test_list with nested elements.
 Print the original test list.
 Call the multiply_nested_list() function with the test_list as an argument and store
the result in a variable res.
 Print the total element product in lists by converting the res variable to a string and
concatenating it with a message.
 Python3

# function to calculate the product of all elements in the nested list

def multiply_nested_list(nested_list):

res = 1

for i in nested_list:

if isinstance(i, list):

res *= multiply_nested_list(i)

else:

res *= i

return res

# initializing list

test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]

# printing original list


print("The original list : " + str(test_list))

# call the function to get the product

res = multiply_nested_list(test_list)

# print result

print("The total element product in lists is : " + str(res))

Output
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880
Time Complexity: O(n) where n is the number of elements in the nested list.
Auxiliary Space: O(d) where d is the depth of the nested list.

Transpose a matrix in Single line in Python


Last Updated : 16 Aug, 2023



Transpose of a matrix is a task we all can perform very easily in Python (Using a
nested loop). But there are some interesting ways to do the same in a single line.
In Python, we can implement a matrix as a nested list (a list inside a list). Each
element is treated as a row of the matrix. For example m = [[1, 2], [4, 5], [3, 6]]
represents a matrix of 3 rows and 2 columns. The first element of the list – m[0] and
the element in the first row, first column – m[0][0].
Example
Input: [[1,2],[3,4],[5,6]]
Output: [[1,3,5],[2,4,6]]
Explanation: Suppose we are given a matrix
[[1, 2],
[3, 4],
[5, 6]]
Then the transpose of the given matrix will be,
[[1, 3, 5],
[2, 4, 6]]
Python Programs to Transpose a Matrix in Single Line
There are various approaches to find the Transpose of a matrix in a single line in
Python. In this article, we will discuss all the approaches which are specific to
transposing a matrix in a single line in Python.
 Using List Comprehension
 Using zip
 Using NumPy
 Using itertools
Transpose Matrix In Single Line using List Comprehension
List comprehension is used to iterate through each element in the matrix. In the given
example, we iterate through each element of matrix (m) in a column-major manner
and assign the result to the rez matrix which is the transpose of m.
 Python3

m = [[1, 2], [3, 4], [5, 6]]

for row in m:

print(row)

rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]

print("\n")

for row in rez:

print(row)

Output:
[1, 2]
[3, 4]
[5, 6]
[1, 3, 5]
[2, 4, 6]
Transpose a matrix in Single line in Python using zip
Python Zip returns an iterator of tuples, where the i-th tuple contains the i-th element
from each of the argument sequences or iterables. In this example we unzip our array
using * and then zip it to get the transpose.
 Python3

matrix = [(1, 2, 3), (4, 5, 6),

(7, 8, 9), (10, 11, 12)]

for row in matrix:

print(row)

print("\n")

t_matrix = zip(*matrix)

for row in t_matrix:

print(row)

Output:
Note :- If you want your result in the form [[1,4,7,10][2,5,8,11][3,6,9,12]] , you can
use t_matrix=map(list, zip(*matrix)).
(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
(10, 11, 12)
(1, 4, 7, 10)
(2, 5, 8, 11)
(3, 6, 9, 12)
Python Programs to Transpose a matrix using NumPy
Python NumPy is a general-purpose array-processing package designed to efficiently
manipulate large multi-dimensional arrays.
Example 1: The transpose method returns a transposed view of the passed multi-
dimensional matrix.
 Python3
import numpy

matrix = [[1, 2, 3], [4, 5, 6]]

print(matrix)

print("\n")

print(numpy.transpose(matrix))

Output:
[[1, 2, 3], [4, 5, 6]]
[[1 4]
[2 5]
[3 6]]
Example 2: Using “.T” after the variable
 Python3

import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])

print(matrix)

print("\n")

print(matrix.T)

Output:
As you can see that both the output are same.
[[1 2 3] [4 5 6]]
[[1 4]
[2 5]
[3 6]]
Fastest way to Transpose a Matrix using Itertools
Python itertools is a module that provides various functions that work on iterators to
produce complex iterators. chain() is a function that takes a series of iterables and
returns one iterable.
In this example, we are using chain() function to convert all the values inside the
matrix into a single list and then transpose the matrix. This method is way faster then
other methods.
 Python3

from itertools import chain

import time

import numpy as np

def transpose2(M):

n = len(M[0])

L = list(chain(*M))

return [L[i::n] for i in range(n)]

start = time.time_ns()

matrix = np.array([[1, 2, 3], [4, 5, 6]])

end = time.time_ns()

print(transpose2(matrix))

print("Time taken", end-start, "ns")


Output
[[1, 4], [2, 5], [3, 6]]
Time taken 108570 ns
Python | Matrix creation of n*n
Last Updated : 26 Feb, 2023



Many times while working with numbers in data science we come across the problem
in which we need to work with data science we need to transform a number to a
matrix of consecutive numbers and hence this problem has a good application. Let’s
discuss certain ways in which this problem can be solved.
Method #1: Using list comprehension List comprehension can be used to
accomplish this particular task by using the range function for each list that needs to
be constructed consecutively.
 Python3

# Python3 code to demonstrate

# matrix creation of n * n

# using list comprehension

# initializing N

N =4

# printing dimension

print("The dimension : " + str(N))


# using list comprehension

# matrix creation of n * n

res = [list(range(1 + N * i, 1 + N * (i + 1)))

for i in range(N)]

# print result

print("The created matrix of N * N: " + str(res))

Output
The dimension : 4
The created matrix of N * N: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11,
12], [13, 14, 15, 16]]
Time Complexity: O(n*n)
Auxiliary Space: O(n*n)
Method #2 : Using next() + itertools.count() The count function can be used start
the count of numbers and next function does the task of creation of sublist
consecutively. List comprehension handles the processing.
 Python3

# Python3 code to demonstrate

# matrix creation of n * n

# using next() + itertools.count()

import itertools
# initializing N

N =4

# printing dimension

print("The dimension : " + str(N))

# using next() + itertools.count()

# matrix creation of n * n

temp = itertools.count(1)

res = [[next(temp) for i in range(N)] for i in range(N)]

# print result

print("The created matrix of N * N: " + str(res))

Output
The dimension : 4
The created matrix of N * N: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11,
12], [13, 14, 15, 16]]
Method #3 Using a list comprehension and the enumerate() function:
In this code, the list comprehension iterates over the rows of the matrix (using the
enumerate() function to get the index of each row), and generates the elements of the
row using a nested list comprehension. The nested list comprehension iterates over the
columns of the matrix and generates the elements of the column using the formula i *
n + j, where i is the index of the row and j is the index of the column.
 Python3

# Initialize the size of the matrix

n =4

# Create the matrix using a list comprehension and the enumerate() function

matrix = [[i * n + j for j in range(1, n+1)] for i, _ in enumerate(range(n))]

# Print the matrix

print("The created matrix of N * N: "+ str(matrix))

#This code is contributed by Edula Vinay Kumar Reddy

Output
The created matrix of N * N: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11,
12], [13, 14, 15, 16]]
Time complexity: O(N^2)
Auxiliary Space: O(N^2)
Method #4 : Using for loop, while loop and slicing
 Python3

# Python3 code to demonstrate

# matrix creation of n * n

# initializing N
N =4

# printing dimension

print("The dimension : " + str(N))

# using list comprehension

# matrix creation of n * n

x=N*N

y=[]

for i in range(1,x+1):

y.append(i)

res=[]

i=0

while(i<len(y)):

a=y[i:i+N]

res.append(a)

i+=N

# print result

print("The created matrix of N * N: " + str(res))

Output
The dimension : 4
The created matrix of N * N: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11,
12], [13, 14, 15, 16]]
Time Complexity : O(N*N)
Auxiliary Space : O(N)
Method #5 : Using nested for loop:
1.Initialize the value of N.
2.Create an empty list called ‘res’ to store the matrix.
3.Using nested for loops, create a matrix with dimensions N x N, and populate it with
values from 1 to N x N, in row-major order.
a. For each row i, create an empty list called ‘row’.
b. For each column j in row i, append the value 1 + N * i + j to the list ‘row’.
c. Append the list ‘row’ to the list ‘res’.
4.Print the created matrix using the print() function.

 Python3

# Python3 code to demonstrate

# matrix creation of n * n

# using nested for loops

# initializing N

N =4

# printing dimension

print("The dimension : " + str(N))

# initializing empty matrix


res = []

for i in range(N):

row = []

for j in range(N):

row.append(1 + N * i + j)

res.append(row)

# print result

print("The created matrix of N * N: " + str(res))

#This code is contributed by Jyothi pinjala.

Output
The dimension : 4
The created matrix of N * N: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11,
12], [13, 14, 15, 16]]
Time Complexity:
The time complexity of the given code is O(N^2), since it iterates over N rows and N
columns in the nested for loops.
Python | Get Kth Column of Matrix
Last Updated : 17 Apr, 2023



Sometimes, while working with Python Matrix, one can have a problem in which one
needs to find the Kth column of Matrix. This is a very popular problem in Machine
Learning Domain and having solution to this is useful. Let’s discuss certain ways in
which this problem can be solved.
Method #1 : Using list comprehension This problem can be solved using list
comprehension in which we can iterate through all the rows and selectively gather all
the elements occurring at Kth index.
 Python3

# Python3 code to demonstrate working of

# Get Kth Column of Matrix

# using list comprehension

# initialize list

test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]

# printing original list

print("The original list is : " + str(test_list))

# initialize K

K =2

# Get Kth Column of Matrix

# using list comprehension

res = [sub[K] for sub in test_list]


# printing result

print("The Kth column of matrix is : " + str(res))

Output :
The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [6, 10, 5]
Time complexity: O(n), where n is the number of elements in the matrix.
Auxiliary space: O(1), as only constant space is used to store the input matrix and the
integer K.
Method #2 : Using zip() This task can also be performed using zip(). This does the
similar task of gathering elements like is done by above list comprehension and offers
compact but slower execution. Works with Python2 only.
 Python

# Python code to demonstrate working of

# Get Kth Column of Matrix

# using zip()

# initialize list

test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]

# printing original list

print("The original list is : " + str(test_list))


# initialize K

K =2

# Get Kth Column of Matrix

# using zip()

res = list(zip(*test_list)[K])

# printing result

print("The Kth column of matrix is : " + str(res))

Output :
The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [6, 10, 5]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of
elements in the res list
Method #3: Using numpy
Note: First Install numpy module using command “pip install numpy”
This problem can also be solved using numpy library which provides a very efficient
and easy way to get the Kth column of matrix.

 Python3

import numpy as np
# initialize list

test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]

# printing original list

print("The original list is : " + str(test_list))

#initialize K

K =2

# Get Kth Column of Matrix

# using numpy

res = np.array(test_list)[:,K]

# printing result

print("The Kth column of matrix is : " + str(res))

#This code is contributed by Edula Vinay Kumar Reddy

Output:
The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [ 6 10 5]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) where n is the length of the list test_list
Method 4: Using a for loop.
This code uses a for loop to iterate over the rows of the matrix and extract the Kth
element from each row using indexing. The extracted elements are then appended to a
new list called res. The final output is the list res containing the Kth column of the
matrix.

 Python3
test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]

K =2

res = []

for i in range(len(test_list)):

res.append(test_list[i][K])

print("The Kth column of matrix is : " + str(res))

Output
The Kth column of matrix is : [6, 10, 5]
Time complexity: O(n), where n is the number of rows in the matrix.
Auxiliary space: O(n), because the list “res” will have at most n elements.
Method #6: Using the built-in function map()
Use the map() function to apply a lambda function that extracts the Kth element from
each sublist in the matrix. The resulting map object is then converted to a list to
obtain the final result.

 Python3

# initialize list

test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]


# printing original list

print("The original list is : " + str(test_list))

# initialize K

K =2

# Get Kth Column of Matrix using map()

res = list(map(lambda x: x[K], test_list))

# printing result

print("The Kth column of matrix is : " + str(res))

Output
The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [6, 10, 5]
The time complexity of this code is O(n), where n is the total number of elements in
the input matrix.
The space complexity of this code is O(n), where n is the total number of elements in
the input matrix.
Method 6: Using list slicing
Step-by-step approach:
1. Initialize the list to store the kth column of the matrix
2. Loop through each row in the matrix
3. Append the element at index k of the row to the list initialized in step 1
4. Return the list as the kth column of the matrix
Below is the implementation of the above approach:

 Python3

# Python code to demonstrate working of

# Get Kth Column of Matrix

# using list slicing

# initialize list

test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]

# printing original list

print("The original list is : " + str(test_list))

# initialize K

K =2

# Get Kth Column of Matrix

# using list slicing

res = [row[K] for row in test_list]


# printing result

print("The Kth column of matrix is : " + str(res))

Output
The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [6, 10, 5]
Time complexity: O(n), where n is the number of elements in the matrix.
Auxiliary space: O(n), where n is the number of elements in the matrix.
Python – Vertical Concatenation in Matrix
Last Updated : 24 Mar, 2023



Given a String Matrix, perform column-wise concatenation of strings, handling


variable lists lengths.
Input : [[“Gfg”, “good”], [“is”, “for”]]
Output : [‘Gfgis’, ‘goodfor’]
Explanation : Column wise concatenated Strings, “Gfg” concatenated with “is”, and
so on.
Input : [[“Gfg”, “good”, “geeks”], [“is”, “for”, “best”]]
Output : [‘Gfgis’, ‘goodfor’, “geeksbest”]
Explanation : Column wise concatenated Strings, “Gfg” concatenated with “is”, and
so on.
Method #1: Using loop
This is brute way in which this task can be performed. In this, we iterate for all the
columns and perform concatenation.

 Python3

# Python3 code to demonstrate working of


# Vertical Concatenation in Matrix

# Using loop

# initializing lists

test_list = [["Gfg", "good"], ["is", "for"], ["Best"]]

# printing original list

print("The original list : " + str(test_list))

# using loop for iteration

res = []

N =0

while N != len(test_list):

temp = ''

for idx in test_list:

# checking for valid index / column

try: temp = temp + idx[N]

except IndexError: pass


res.append(temp)

N =N +1

res = [ele for ele in res if ele]

# printing result

print("List after column Concatenation : " + str(res))

Output
The original list : [['Gfg', 'good'], ['is', 'for'], ['Best']]
List after column Concatenation : ['GfgisBest', 'goodfor']
Time Complexity: O(n2)
Space Complexity: O(n)
Method #2 : Using join() + list comprehension + zip_longest()
The combination of above functions can be used to solve this problem. In this, we
handle the null index values using zip_longest, and join() is used to perform task of
concatenation. The list comprehension drives one-liner logic.

 Python3

# Python3 code to demonstrate working of

# Vertical Concatenation in Matrix

# Using join() + list comprehension + zip_longest()

from itertools import zip_longest


# initializing lists

test_list = [["Gfg", "good"], ["is", "for"], ["Best"]]

# printing original list

print("The original list : " + str(test_list))

# using join to concaternate, zip_longest filling values using

# "fill"

res = ["".join(ele) for ele in zip_longest(*test_list, fillvalue ="")]

# printing result

print("List after column Concatenation : " + str(res))

Output
The original list : [['Gfg', 'good'], ['is', 'for'], ['Best']]
List after column Concatenation : ['GfgisBest', 'goodfor']
Time Complexity: O(n2) -> (loop+join)
Space Complexity: O(n)
Method #3: Using numpy.transpose() and numpy.ravel()
Step-by-step approach:
 Import the numpy library.
 Initialize the list.
 Find the maximum length of a sublist using a list comprehension and
the max() function.
 Pad each sublist with empty strings to make them the same length using another
list comprehension.
 Convert the padded list to a numpy array using the np.array() function.
 Use the transpose (T) method to switch rows and columns.
 Use a list comprehension and join to concatenate the strings in each row of the
transposed array.
 Print the result.
Below is the implementation of the above approach:

 Python3

import numpy as np

# initializing list

test_list = [["Gfg", "good"], ["is", "for"], ["Best"]]

# find the maximum length of a sublist

max_len = max(len(sublist) for sublist in test_list)

# pad the sublists with empty strings to make them the same length

padded_list = [sublist + [''] * (max_len - len(sublist)) for sublist in test_list]

# convert the list to a numpy array

arr = np.array(padded_list)

# use transpose to switch rows and columns


arr_t = arr.T

# use join to concatenate the strings in each row

res = [''.join(row) for row in arr_t]

# print the result

print("List after column concatenation: " + str(res))

OUTPUT:
List after column concatenation: ['GfgisBest', 'goodfor']
Time complexity: O(n^2), where n is the number of elements in the input list.
Auxiliary space: O(n), for the numpy array and the padded list.

You might also like