Python Programs
Python Programs
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
num1 = 15
num2 = 12
# printing values
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
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
def add(a,b):
return a+b
num1 = 10
num2 = 5
sum_of_twonumbers = add(num1,num2)
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
num2 = 12
import operator
su = operator.add(num1,num2)
# printing values
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
add_numbers = lambda x, y: x + y
num2 = 2
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
if y == 0:
return x
else:
return add_numbers_recursive(x + 1, y - 1)
# Take input from the user
num1 = 1
num2 = 2
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
num1 = 15
num2 = 12
# printing values
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
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
return a+b
num1 = 10
num2 = 5
sum_of_twonumbers = add(num1,num2)
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
num2 = 12
import operator
su = operator.add(num1,num2)
# printing values
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
add_numbers = lambda x, y: x + y
# Take input from the user
num1 = 1
num2 = 2
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
if y == 0:
return x
else:
return add_numbers_recursive(x + 1, y - 1)
num1 = 1
num2 = 2
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
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
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
# Driver code
a =2
b =4
Output
4
Time complexity: O(1)
Auxiliary space: O(1)
Maximum of two numbers Using lambda function
Python3
a=2;b=4
maximum = lambda a,b:a if a > b else b
Output:
4 is a maximum number
Maximum of two numbers Using list comprehension
Python3
a=2;b=4
Output
maximum number is: [4]
Maximum of two numbers Using sort() method
Python3
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
# 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))
res = 1
def factorial(n):
# Driver Code
num = 5
print ("Factorial of",num,"is",
factorial(num))
def factorial(n):
return(math.factorial(n))
# Driver Code
num = 5
print("Factorial of", num, "is",
factorial(num))
# Driver Code
num = 5
print("Factorial of", num, "is", factorial(num))
Output
Factorial of 5 is 120
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
# rate of interest.
def simple_interest(p,t,r):
si = (p * t * r)/100
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
def simple_interest(p,t,r):
si = (p * t * r)/100
# Driver code
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
CI = Amount - principal
compound_interest(10000, 10.25, 5)
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
CI = Amount - principal
# Driver Code
#Function Call
compound_interest(principal,rate,time)
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
# inputs
t= 2 # time
r= 5.4 # rate
print(ci)
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
Amount = principal
for i in range(time):
CI = Amount - principal
# Driver Code
compound_interest(1200, 5.4, 2)
Output
Compound interest is 133.0992000000001
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
# the power y
return 1
if y % 2 == 0:
def order(x):
n =0
while (x != 0):
n =n +1
x = x // 10
return n
# Function to check whether the given
def isArmstrong(x):
n = order(x)
temp = x
sum1 = 0
r = temp % 10
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)
Python3
# python 3 program
# to check whether the given number is armstrong or not
b = len(str(n))
sum1 = 0
while n != 0:
r = n % 10
sum1 = sum1+(r**b)
n = n//10
if s == sum1:
else:
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
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)
Python3
import math
def isArmstrong(num):
n = num
numDigits = 0
sum = 0
while n > 0:
n //= 10
numDigits += 1
n = num
while n > 0:
digit = n % 10
n //= 10
# Check if num is Armstrong number or not
if sum == num:
return True
return False
# Example 1
num1 = 1634
if isArmstrong(num1):
else:
# Example 2
num2 = 120
if isArmstrong(num2):
else:
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)
Python3
def is_armstrong_number(number):
# Example usage:
num = 153
if is_armstrong_number(num):
else:
Output
153 is an Armstrong number
Python Program to Find Sum of Array
Last Updated : 03 Jul, 2023
def _sum(arr):
# initialize a variable
sum = 0
# one at a time
for i in arr:
sum = sum + i
return(sum)
# main function
if __name__ == "__main__":
ans = _sum(arr)
# display sum
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
# the value
ans = sum(arr)
# display sum
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
def _sum(arr):
# iterate over array
# sum on accumulator
return(sum)
# driver function
arr = []
n = len(arr)
ans = _sum(arr)
# display sum
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
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
if low == high:
return arr[low]
#Examples
arr = [1, 2, 3]
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
c = Counter(arr)
sum = 0
Output
Sum of the array is 34
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
# in arr[] of size n
# in arr[] of size n
max = arr[0]
# Traverse array elements from second
# current max
max = arr[i]
return max
# Driver Code
n = len(arr)
Ans = largest(arr, n)
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
# in arr[] of size n
ans = max(arr)
return ans;
# Driver code
if __name__ == '__main__':
n = len(arr)
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
arr.sort()
return arr[n-1]
# or return arr[-1]
# Driver Code
n = len(arr)
Ans = largest(arr, n)
# in arr[] of size n
def largest(arr):
return ans
n = len(arr)
Ans = largest(arr)
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
import operator
max=0
for i in arr:
if operator.gt(i,max):
max=i
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
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
no_of_reverse = end-start+1
count = 0
while((no_of_reverse)//2 != count):
return arr
start = 0
end = size-1
# based on no of rotations.
end = size-d-1
start = size-d
end = size-1
return arr
arr = [1, 2, 3, 4, 5, 6, 7, 8]
size = 8
d =1
else:
d = d % size
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.
Python3
temp = []
i =0
temp.append(arr[i])
i =i +1
i =0
arr[i] = arr[d]
i =i +1
d =d +1
arr = [1, 2, 3, 4, 5, 6, 7]
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*/
for i in range(d):
leftRotatebyOne(arr, n)
temp = arr[0]
for i in range(n-1):
arr[i] = arr[i+1]
arr[n-1] = temp
def printArray(arr,size):
for i in range(size):
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 * 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}
Python3
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
for i in range(size):
if b == 0:
return a
else:
return gcd(b, a % b)
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
def rotateList(arr,d,n):
arr[:]=arr[d:n]+arr[0:d]
return arr
arr = [1, 2, 3, 4, 5, 6]
print(arr)
print(rotateList(arr,2,len(arr)))
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
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
Output
3
4
5
6
7
1
2
Python Program for Reversal Algorithm Using collections.deque
Python3
from collections import deque
# 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
# part to end.
x = arr[0]
arr[j] = arr[j + 1]
arr[n-1] = x
# main
n = len(arr)
position = 2
splitArr(arr, n, position)
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
# part to end.
return (a[k::]+b[::])
# main
n = len(arr)
position = 2
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
# 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:
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
n =2
result = split_and_add(arr, n)
print(*result)
Output
5 6 52 36 12 10
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'.
product = 1
for i in range(len):
return product % n
len = len(arr)
n = 11
# Python3 program to
# are multiplied.
# * .. * arr[n-1]
mul = 1
for i in range(lens):
return mul % n
# Driven code
lens = len(arr)
n = 11
# of after multiple
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
return result
# Driver Code
n1 = 11
print(result1)
arr2 = [100, 10]
n2 = 5
print(result2)
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]
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):
# Driver program
A = [6, 5, 4, 4]
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
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))
# 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
# 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
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
# Swap function
def swapList(newList):
return newList
# Driver code
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
def swapList(list):
return list
# Driver code
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
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
# Swap function
def swapList(list):
return list
# Driver code
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
# Swap function
def swapList(list):
first = list.pop(0)
last = list.pop(-1)
list.insert(0, last)
list.append(first)
return list
# Driver code
print(swapList(newList))
Output
[24, 35, 9, 56, 12]
Python3
def swap_first_last_3(lst):
if len(lst) >= 2:
return lst
result=swap_first_last_3(inp)
Output
The original input is: [12, 35, 9, 56, 24]
The output after swap first and last is: [24, 35, 9, 56, 12]
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
return list
# Driver function
pos1, pos2 = 1, 3
Output:
# at given positions
# Swap function
first_ele = list.pop(pos1)
second_ele = list.pop(pos2-1)
list.insert(pos1, second_ele)
list.insert(pos2, first_ele)
return list
# Driver function
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
Output:
# given positions
# Swap function
return list
# Driver Code
pos1, pos2 = 1, 3
Output:
# Swap function
temp=lis[pos1]
lis[pos1]=lis[pos2]
lis[pos2]=temp
return lis
# Driver function
pos1, pos2 = 1, 3
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
pos1, pos2 = 1, 3
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()
n = len(li)
# Initializing list
test_list = [1, 4, 5, 7, 8]
# Printing test_list
# Initializing counter
counter = 0
for i in test_list:
# incrementing counter
counter = counter + 1
# Printing length of list
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
# Initializing list
test_list = [1, 4, 5, 7, 8]
# Printing test_list
list_len_hint = length_hint(test_list)
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
# using sum()
Output:
The list is : [1, 4, 5, 7, 8]
Length of list using len() is : 5
Length of list using length_hint() is : 5
# 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
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):
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:])
lst = [1, 2, 3, 4, 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
list1 = [1, 4, 5, 7, 8]
s =0
for i, a in enumerate(list1):
s += 1
print(s)
Output
5
test_list = [1, 4, 5, 7, 8]
list_len = sum(Counter(test_list).values())
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
# 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)
# using len()
start_time_len = time.time()
list_len = len(test_list)
# using length_hint()
start_time_hint = time.time()
list_len_hint = length_hint(test_list)
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.
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
# Initializing list
test_list_set = [ 1, 6, 3, 5, 3, 4 ]
test_list_bisect = [ 1, 6, 3, 5, 3, 4 ]
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
# Calculating frequencies
frequency = Counter(test_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
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
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: []
Output
List1 before deleting is : [1, 2, 3]
List1 after clearing using reinitialization : []
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 : []
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 : []
# 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 : []
Output
List before clearing: [1, 2, 3, 4, 5]
List after clearing using Slicing: []
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.
new_lst = lst[::-1]
return new_lst
print(Reverse(lst))
Output
[15, 14, 13, 12, 11, 10]
def list_reverse(arr,size):
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]
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
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.reverse()
Output
Using reverse() [15, 14, 13, 12, 11, 10]
Using reversed() [10, 11, 12, 13, 14, 15]
def reverse_list(arr):
left = 0
right = len(arr)-1
# 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=list(map(int,input().split()))
l = [] # empty list
for i in lst:
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
new_list = [original_list[len(original_list) - i]
print(new_list)
Output
[15, 14, 13, 12, 11, 10]
import numpy as np
# Input list
my_list = [4, 5, 6, 7, 8, 9]
my_array = np.array(my_list)
reversed_array = my_array[::-1]
reversed_list = reversed_array.tolist()
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
print(A)
print(B)
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
print(A)
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
print()
print()
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
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.
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
[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]]
for i in range(len(X)):
for j in range(len(X[0])):
print(r)
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.
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
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
for r in result:
print(r)
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
# using zip()
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
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
# 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]]
print(result)
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]))
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
X = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Y = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
matrix_x = Matrix(X)
matrix_y = Matrix(Y)
print(result)
Output:
Matrix([
[10, 10, 10],
[10, 10, 10],
[10, 10, 10]])
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]]
A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
for A_row in A]
for r in result:
print(r)
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
import numpy as np
A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
[6, 7, 3, 0],
[4, 5, 9, 1]]
result= [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
result = np.dot(A,B)
for r in result:
print(r)
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
if len(A[0]) != len(B):
if i >= len(A):
return
if j >= len(B[0]):
if k >= len(B):
multiply(A, B, result, 0, 0, 0)
return result
# example usage
result = matrix_multiply_recursive(A, B)
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
# Matrix Product
def prod(val):
res = 1
res *= ele
return res
# initializing list
# Matrix Product
res = prod([ele for sub in test_list for ele in sub])
# print result
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
# Matrix Product
# getting Product
def prod(val):
res = 1
res *= ele
return res
# initializing list
# Matrix Product
res = prod(list(chain(*test_list)))
# print result
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
# Matrix Product
# initializing list
x = []
for i in test_list:
x.extend(i)
res = 1
for j in x:
res *= j
# print result
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
# Matrix Product
# initializing list
import operator
x = []
for i in test_list:
x.extend(i)
res = reduce(operator.mul, x, 1)
# print result
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
# Matrix Product
# initializing list
res = 1
for i in test_list:
for j in i:
res *= j
# print result
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
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
res = multiply_nested_list(test_list)
# print result
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 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
for row in m:
print(row)
print("\n")
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
print(row)
print("\n")
t_matrix = zip(*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
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
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
import time
import numpy as np
def transpose2(M):
n = len(M[0])
L = list(chain(*M))
start = time.time_ns()
end = time.time_ns()
print(transpose2(matrix))
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
# matrix creation of n * n
# initializing N
N =4
# printing dimension
# matrix creation of n * n
for i in range(N)]
# print result
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
# matrix creation of n * n
import itertools
# initializing N
N =4
# printing dimension
# matrix creation of n * n
temp = itertools.count(1)
# print result
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
n =4
# Create the matrix using a list comprehension and the enumerate() function
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
# matrix creation of n * n
# initializing N
N =4
# printing dimension
# 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
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
# matrix creation of n * n
# initializing N
N =4
# printing dimension
for i in range(N):
row = []
for j in range(N):
row.append(1 + N * i + j)
res.append(row)
# print result
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
# initialize list
# initialize K
K =2
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
# using zip()
# initialize list
K =2
# using zip()
res = list(zip(*test_list)[K])
# printing result
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
#initialize K
K =2
# using numpy
res = np.array(test_list)[:,K]
# printing result
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])
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
# initialize K
K =2
# printing result
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
# initialize list
# initialize K
K =2
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
Python3
# Using loop
# initializing lists
res = []
N =0
while N != len(test_list):
temp = ''
N =N +1
# printing result
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
# "fill"
# printing result
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
# pad the sublists with empty strings to make them the same length
arr = np.array(padded_list)
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.