# Vikram Chiluka

## Compare and get Differences between two Lists in Python

Lists in Python:

Lists are the most versatile ordered list object type in Python. It’s also known as a sequence, which is an ordered group of objects that can contain objects of any data form, including Python Numbers, Python Strings, and nested lists. One of the most widely used and flexible Python Data Types is the list.

Examples:

Input:

list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]

Output:

Printing the Differences between the lists :
['Geeks', 'is', 'BTechGeeks', 'online', 'Platform', 'world', 'Python', 'Coding', 'Language']

## Compare and get Differences between two Lists in Python

Let’s say we have two lists

There may be certain items in the first list that are not present in the second list. There are also several items that are present in the second list but not in the first list. We’d like to compare our two lists to figure out what the variations are.

There are several ways to compare and get differences between two lists some of them are:

### Method #1:Using union function in sets

When we make a set from a list, it only includes the list’s unique elements. So, let’s transform our lists into sets, and then subtract these sets to find the differences.
We discovered the variations between the two lists, i.e. elements that are present in one list but not in the other.

Below is the implementation:

# given two lists
list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]
# converting two lists to sets
setlist1 = set(list1)
setlist2 = set(list2)
# getting the differences in both lists
listDif = (setlist1 - setlist2).union(setlist2 - setlist2)
print('Printing the Differences between the lists : ')
print(listDif)


Output:

Printing the Differences between the lists :
['Geeks', 'is', 'BTechGeeks', 'online', 'Platform', 'world', 'Python', 'Coding', 'Language']

### Method #2:Using set.difference()

Instead of subtracting two sets with the â€“ operator in the previous solution, we can get the differences by using the setÂ difference() feature.

So, let’s convert our lists to sets, and then use the difference() function to find the differences between two lists.

Below is the implementation:

# given two lists
list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]
# converting two lists to sets
setlist1 = set(list1)
setlist2 = set(list2)
# getting elements in first list which are not in second list
difference1 = setlist1.difference(setlist2)
# getting elements in second list which are not in first list
difference2 = setlist2.difference(setlist1)
listDif = difference1.union(difference2)
print('Printing the Differences between the lists : ')
print(listDif)


Output:

Printing the Differences between the lists :
['Geeks', 'is', 'BTechGeeks', 'online', 'Platform', 'world', 'Python', 'Coding', 'Language']

### Method #3:Using List Comprehension

To find the differences, we can iterate over both lists and search for elements in other lists. However, we can use list comprehension for iteration.

Below is the implementation:

# given two lists
list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]

# getting elements in first list which are not in second list
difference1 = [element for element in list1 if element not in list2]
# getting elements in second list which are not in first list
difference2 = [element for element in list2 if element not in list1]
listDif = difference1+difference2
print('Printing the Differences between the lists : ')
print(listDif)


Output:

Printing the Differences between the lists :
['Geeks', 'is', 'BTechGeeks', 'online', 'Platform', 'world', 'Python', 'Coding', 'Language']

### Method #4:Using set.symmetric_difference()

We had all of the variations between two lists in two steps in all of the previous solutions. Using symmetric difference(), however, we can accomplish this in a single stage.
Set has a member function called symmetric difference() that takes another sequence as an argument. It returns a new set containing elements from either the calling set object or the sequence statement, but not both. In other words, it returns the differences between set and list. Let’s see if we can use this to determine the differences between two lists.

Below is the implementation:

# given two lists
list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]

listDif = set(list1).symmetric_difference(list2)
print('Printing the Differences between the lists : ')
print(listDif)


Output:

Printing the Differences between the lists :
{'is', 'online', 'world', 'BTechGeeks', 'Python', 'Language', 'Coding', 'Geeks', 'Platform'}

### Method #5:Using set and ^ operator

Quick approach for solving this problem is to use ^ and sets.

Below is the implementation:

# given two lists
list1 = ["Hello", "Geeks", "this", "is", "BTechGeeks", "online", "Platform"]
list2 = ["Hello", "world", "this", "Python", "Coding", "Language"]

listDif = set(list1) ^ set(list2)
print('Printing the Differences between the lists : ')
print(listDif)


Output:

Printing the Differences between the lists :
{'is', 'online', 'world', 'BTechGeeks', 'Python', 'Language', 'Coding', 'Geeks', 'Platform'}

## Python Program to Check Armstrong Number

Armstrong Number:

Beginners sometimes ask what the Armstrong number, also known as the narcissist number, is. Because of the way the number behaves in a given number base, it is particularly interesting to new programmers and those learning a new programming language. The Armstrong number meaning in numerical number theory is the number in any given number base that forms the sum of the same number when each of its digits is raised to the power of the number’s digits.

Ex: 153, 371 etc.

Example1:

Input:

number =153

Output:

153 is Armstrong number

Explanation:

Here 1^3 + 5^3 + 3^3 = 153  so it is Armstrong Number

Example2:

Input:

number =79

Output:

79 is not Armstrong number

Explanation:

Here 7^2 + 9^2 = 130 not equal to 79  so it is not Armstrong Number

## Armstrong Number in Python

Below are the ways to check Armstrong number in python

Explore more instances related to python concepts fromÂ Python Programming ExamplesÂ Guide and get promoted from beginner to professional programmer level in Python Programming Language.

### Method #1: Using while loop

1. Count how many digits there are in the number.
2. Using mod and division operations, each digit is accessed one after the other.
3. Each digit is multiplied by the number of digits, and the result is saved in a separate variable.
4. Steps 2 and 3 are repeated until all of the digits have been used.
5. Analyze the result obtained using the original number.
• If both are same/equal then it is armstrong number
• Else it is not armstrong number.

Below is the implementation:

# given number
num = 153
# intialize result to zero(ans)
ans = 0
# calculating the total digits in the given number
digits = len(str(num))
# copy the number in another variable(duplicate)
dup_number = num
while (dup_number != 0):

# getting the last digit
remainder = dup_number % 10

# multiply the result by a digit raised to the power of the number of digits.
ans = ans + remainder**digits
dup_number = dup_number//10
# It is Armstrong number if it is equal to original number
if(num == ans):
print(num, "is Armstrong number")
else:
print(num, "is not Armstrong number")


Output:

153 is Armstrong number

### Method #2: By converting the number to string and Traversing the string to extract the digits

Algorithm:

• Initialize a variable sayÂ ansÂ to 0
• Using a new variable, we must convert the given number to a string.
• Calculate the digits of the given number.
• Iterate through the string, convert each character to an integer, multiply theÂ ans by a digit raised to the power of the number of digits of the given number.
• If theÂ ans is equal to given number then it is Armstrong number

Below is the implementation:

# given number
num = 153
# intialize result to zero(ans)
ans = 0
# converting given number to string
numString = str(num)
# calculating the number of digits of the given number
digits = len(numString)
# Traverse through the string
for char in numString:
# Converting the character of string to integer
# multiply the ans by a digit raised to the power of digits.
ans = ans+int(char)**digits

# It is Armstrong number if it is equal to original number
if(num == ans):
print(num, "is Armstrong number")
else:
print(num, "is not Armstrong number")


Output:

153 is Armstrong number

Related Programs:

## Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary

Dictionaries in Python:

Dictionary is a mutable built-in Python Data Structure. It is conceptually related to List, Set, and Tuples. It is, however, indexed by keys rather than a sequence of numbers and can be thought of as associative arrays. On a high level, it consists of a key and its associated value. The Dictionary class in Python represents a hash-table implementation.

Examples:

Example1:

Input:

given string ="hello this is hello BTechGeeks BTechGeeks BTechGeeks this python programming python language"

Output:

{'hello': 2, 'this': 2, 'is': 1, 'BTechGeeks': 3, 'python': 2, 'programming': 1, 'language': 1}

Example2:

Input:

given string ="good morning this is good this python python BTechGeeks good good python online coding platform"

Output:

{'good': 4, 'morning': 1, 'this': 2, 'is': 1, 'python': 3, 'BTechGeeks': 1, 'online': 1, 'coding': 1, 'platform': 1}

## Program to Count the Frequency of Words Appearing in a String Using a Dictionary

There are several ways to count the frequency of all words in the given string using dictionary some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

### Method #1:Using count and zip function (Static Input)

Approach:

• Give the string input as static and store it in a variable
• Split the given string into words using split() function
• Convert this into list using list() function.
• Count the frequency of each term using count() function and save the results in a separate list using list Comprehension.
• Merge the lists containing the terms and the word counts into a dictionary using the zip() function.
• The resultant dictionary is printed
• End of Program

Below is the implementation:

# given string
given_string = "hello this is hello BTechGeeks BTechGeeks BTechGeeks this python programming python language"
# Split the given string into words using split() function
# Convert this into list using list() function.
listString = given_string.split()
# Count the frequency of each term using count() function and
# save the results in a separate list using list Comprehension.
freqWords = [listString.count(k) for k in listString]
# Merge the lists containing the terms and the word counts
# into a dictionary using the zip() function.
resultdict = dict(zip(listString, freqWords))
# Print the resultant dictionary
print(resultdict)


Output:

{'hello': 2, 'this': 2, 'is': 1, 'BTechGeeks': 3, 'python': 2, 'programming': 1, 'language': 1}

Explanation:

• A string must be entered by the user and saved in a variable.
• The string is divided into words and saved in the list using a space as the reference.
• Using list comprehension and the count() function, the frequency of each word in the list is counted.
• The complete dictionary is printed after being created with the zip() method.

### Method #2:Using count and zip function (User Input)

Approach:

• Scan the string using input() function.
• Split the given string into words using split() function
• Convert this into list using list() function.
• Count the frequency of each term using count() function and save the results in a separate list using list Comprehension.
• Merge the lists containing the terms and the word counts into a dictionary using the zip() function.
• The resultant dictionary is printed
• End of Program

Below is the implementation:

# Scan the given string using input() function
given_string = input("Enter some random string separated by spaces = ")
# Split the given string into words using split() function
# Convert this into list using list() function.
listString = given_string.split()
# Count the frequency of each term using count() function and
# save the results in a separate list using list Comprehension.
freqWords = [listString.count(k) for k in listString]
# Merge the lists containing the terms and the word counts
# into a dictionary using the zip() function.
resultdict = dict(zip(listString, freqWords))
# Print the resultant dictionary
print(resultdict)


Output:

Enter some random string separated by spaces = good morning this is good this python python BTechGeeks good good python online coding platform
{'good': 4, 'morning': 1, 'this': 2, 'is': 1, 'python': 3, 'BTechGeeks': 1, 'online': 1, 'coding': 1, 'platform': 1}

Related Programs:

## Python Program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple

Tuple in Python:

Tuples, like Python lists, are a common data type that allows you to store values in a series. They could be handy in cases when you want to communicate data with someone but not enable them to change it. They can use the data values, but no change is reflected in the original data that was supplied.

Examples:

Example1:

Input:

Â given list of tuples =[(5, 12, 98), (7, 1), (4, 19, 11, 9), (36, 82, 19, 1, 2, 5, 3, 6, 9, 6)]

Output:

Printing the sorted list of tuples :
[(7, 1), (36, 82, 19, 1, 2, 5, 3, 6, 9, 6), (4, 19, 11, 9), (5, 12, 98)]

Example2:

Input:

 Â given list of tuples =  [(7, 12, 23), (999, 4), (234, 245, 129), (10, 23, 456)]

Output:

Printing the sorted list of tuples :
[(999, 4), (7, 12, 23), (234, 245, 129), (10, 23, 456)]

Example3:

Input:

  Â given list of tuples = [('hello', 'this'), ('BTechGeeks', 'online', 'platform'), ('for', 'students')]

Output:

Printing the sorted list of tuples :
[('BTechGeeks', 'online', 'platform'), ('for', 'students'), ('hello', 'this')]

## Program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple

There are several ways to sort a List of Tuples in ascending order by the last element in each tuple some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

### Method #1:Using sorted function

The Sorted() method sorts a list and always returns a list with the entries sorted without changing the original sequence.

i)List of tuples of Integer type

Approach:

• Give the list of Tuples input as static input.
• Create a function that returns the final element of each tuple in the list.
• Create a new function with the previous function as the key, and sort the list using sorted() function.
• Print the sorted list
• Exit of Program

Below is the implementation:

def lastEle(ele):
# returning the last element
return ele[-1]

def sortlastElementTuple(listTuple):
# using sorted function with first parameter as given list of tuples and
# key as last element
# To get last element we create a function which returns the last element
# returning the sorted list of tuples
return sorted(listTuple, key=lastEle)

listofTuples = [(5, 12, 98), (7, 1), (4, 19, 11, 9),
(36, 82, 19, 1, 2, 5, 3, 6, 9, 6)]
# printing the sorted list of tuples by last element
print("Printing the sorted list of tuples : ")
# Passing the given list of tuples to sortlastElementTuple function
print(sortlastElementTuple(listofTuples))


Output:

Printing the sorted list of tuples :
[(7, 1), (36, 82, 19, 1, 2, 5, 3, 6, 9, 6), (4, 19, 11, 9), (5, 12, 98)]

ii)List of tuples of String type

Below is the implementation:

def lastEle(ele):
# returning the last element
return ele[-1]

def sortlastElementTuple(listTuple):
# using sorted function with first parameter as given list of tuples and
# key as last element
# To get last element we create a function which returns the last element
# returning the sorted list of tuples
return sorted(listTuple, key=lastEle)

listofTuples = [('hello', 'this'), ('BTechGeeks', 'online',
'platform'), ('for', 'students')]
# printing the sorted list of tuples by last element
print("Printing the sorted list of tuples : ")
# Passing the given list of tuples to sortlastElementTuple function
print(sortlastElementTuple(listofTuples))


Output:

Printing the sorted list of tuples :
[('BTechGeeks', 'online', 'platform'), ('for', 'students'), ('hello', 'this')]

### Method #2:Using sort function

The sort() method arranges the items in a list in an ascending or descending order.

We use lambda function to get the last element in the given list of tuples.

i)List of tuples of Integer type

Below is the implementation:

def sortlastElementTuple(listTuple):
# The key has been configured to sort using the
# last element of the sublist lambda has been used
listTuple.sort(key=lambda k: k[-1])
# returning the sorted list of tuples
return listTuple

listofTuples = [(5, 12, 98), (7, 1), (4, 19, 11, 9),
(36, 82, 19, 1, 2, 5, 3, 6, 9, 6)]
# printing the sorted list of tuples by last element
print("Printing the sorted list of tuples : ")
# Passing the given list of tuples to sortlastElementTuple function
print(sortlastElementTuple(listofTuples))


Output:

Printing the sorted list of tuples :
[(7, 1), (36, 82, 19, 1, 2, 5, 3, 6, 9, 6), (4, 19, 11, 9), (5, 12, 98)]

ii)List of tuples of String type

Below is the implementation:

def sortlastElementTuple(listTuple):
# The key has been configured to sort using the
# last element of the sublist lambda has been used
listTuple.sort(key=lambda k: k[-1])
# returning the sorted list of tuples
return listTuple

listofTuples = [('hello', 'this'), ('BTechGeeks', 'online',
'platform'), ('for', 'students')]
# printing the sorted list of tuples by last element
print("Printing the sorted list of tuples : ")
# Passing the given list of tuples to sortlastElementTuple function
print(sortlastElementTuple(listofTuples))


Output:

Printing the sorted list of tuples :
[('BTechGeeks', 'online', 'platform'), ('for', 'students'), ('hello', 'this')]

Related Programs:

## Python Program to Generate Random Numbers from 1 to 20 and Append Them to the List

Lists in Python:

Pythonâ€™s built-in container types are List and Tuple. Objects of both classes can store various additional objects that can be accessed via index. Lists and tuples, like strings, are sequence data types. Objects of different types can be stored in a list or a tuple.

A list is an ordered collection of objects (of the same or distinct types) separated by commas and surrounded by square brackets.

Random Numbers in Python:

The random module in Python defines a set of functions for generating and manipulating random integers. Random(), a pseudo-random number generator function that generates a random float number between 0.0 and 1.0, is used by functions in the random module. These functions are used in a variety of games, lotteries, and other applications that need the creation of random numbers.

Examples:

Example1:

Input:

given number of elements =30

Output:

The random number list which contains 30 elements =  [6, 18, 11, 5, 16, 12, 6, 20, 12, 1, 5, 20, 20, 18, 13, 12, 5, 7,
14, 9, 4, 5, 13, 18, 19, 19, 19, 20, 12, 2]

Example2:

Input:

Enter the total number of elements in the given list =25

Output:

The random number list which contains 25 elements = [1, 6, 18, 5, 3, 2, 7, 5, 6, 6, 1, 2, 4, 17, 1, 20, 6, 2, 6, 19, 6,
10, 19, 20, 3]

## Program to Generate Random Numbers from 1 to 20 and Append Them to the List

We will create a program that generates random numbers from 1 to 20 and adds them to a empty list using append() function.

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

### 1)randint function

Python has a random module that can create random integers. We utilized the random function in combination with the randint function to produce random numbers.

Syntax:

randint(start, end)

randint takes two inputs: a starting and an ending point. Both must be integers, with the first number always being less than the second.

### 2)Generating n random numbers using randint function(Static Input)

Approach:

• ImportÂ the random module to the code.
• Take a empty list which stores the random numbers.
• Using static input, giveÂ the number of elements in the list.
• Loop from 1 to number of elements using for loop
• Generate the random number by passing parameters 1 and 20 to randint function and store it in a variable.
• Append this random number variable to the list.
• Print the random number list

Below is the implementation:

# importing random module
import random
# Take a empty list which stores the random numbers.
randomlist = []
# Using static input, giveÂ the number of elements in the list.
terms = 30
# Loop from 1 to number of elements using for loop
for k in range(terms):
# Generate the random number by passing parameters 1 and 20 to
# randint function and store it in a variable.
randNum = random.randint(1, 20)
# Append this random number variable to the list using append() function
randomlist.append(randNum)
# print the random number list
print('The random number list which contains',
terms, 'elements = ', randomlist)


Output:

The random number list which contains 30 elements =  [6, 18, 11, 5, 16, 12, 6, 20, 12, 1, 5, 20, 20, 18, 13, 12, 5, 7,
14, 9, 4, 5, 13, 18, 19, 19, 19, 20, 12, 2]

Explanation:

• The random module has been included to the code.
• Using static input, giveÂ the number of elements in the list.
• Random.randint() is used in a for loop to produce random numbers, which are then appended to a list.
• The inputs sent to the random.randint() function are used to set the range within which the randomised numbers should be printed.
• The randomised list is then printed.

### 3)Generating n random numbers using randint function(User Input)

Approach:

• ImportÂ the random module to the code.
• Take a empty list which stores the random numbers.
• Scan the number of elements using int(input()).
• Loop from 1 to number of elements using for loop
• Generate the random number by passing parameters 1 and 20 to randint function and store it in a variable.
• Append this random number variable to the list.
• Print the random number list

Below is the implementation:

# importing random module
import random
# Take a empty list which stores the random numbers.
randomlist = []
# Scan the number of elements using int(input()).
terms = int(input('Enter the total number of elements in the given list ='))
# Loop from 1 to number of elements using for loop
for k in range(terms):
# Generate the random number by passing parameters 1 and 20 to
# randint function and store it in a variable.
randNum=random.randint(1, 20)
# Append this random number variable to the list using append() function
randomlist.append(randNum)
# print the random number list
print('The random number list which contains',
terms, 'elements = ', randomlist)


Output:

Enter the total number of elements in the given list =25
The random number list which contains 25 elements = [1, 6, 18, 5, 3, 2, 7, 5, 6, 6, 1, 2, 4, 17, 1, 20, 6, 2, 6, 19, 6, 10,
19, 20, 3]

Related Programs:

## Python Program to Check if a Date is Valid and Print the Incremented Date

Given a date , the task is to Check if a Date is Valid and increment the given date and print it in python

Examples:

Example1:

Input:

given date ="11/02/2001"

Output:

The incremented given date is:  12 / 2 / 2001

Example2:

Input:

 given date = "29/02/2001"

Output:

The given date 29/02/2001 is not valid

## Program to Check and Print the Incremented Date in Python

Below are the ways to check and implement the increment the given date in Python:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

### 1)By using if..elif..else Conditional StatementsÂ  and split() function(Static Input)

Approach:

• Give the date in the format dd/mm/yyyy as static input
• Separate the date by storing the day, month, and year in different variables.
• Check the validity of the day, month, and year using various if-statements.
• If the date is valid, increment it .
• Print the increment date.
• Exit of Program.

Below is the implementation:

# given given_data
given_date = "11/02/2001"
# splitting the given_data by / character to separate given_data,month and year
day, month, year = given_date.split('/')
day = int(day)
month = int(month)
year = int(year)
if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
maxdays = 31
elif(month == 4 or month == 6 or month == 9 or month == 11):
maxdays = 30
elif(year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
maxdays = 29
else:
maxdays = 28
if(month < 1 or month > 12):
print("The given date", given_date, "is not valid")
elif(day < 1 or day > maxdays):
print("The given date", given_date, "is not valid")
elif(day == maxdays and month != 12):
day = 1
month = month+1
print("The incremented given date is: ", day, month, year)
elif(day == 31 and month == 12):
day = 1
month = 1
year = year+1
print("The incremented given date is: ", day, '/', month, '/', year)
else:
day = day + 1
print("The incremented given date is: ",  day, '/', month, '/', year)


Output:

The incremented given date is:  12 / 2 / 2001

Explanation:

• Give the date in the format dd/mm/yyyy as static input.
• The date is then divided, with the day, month, and year recorded in separate variables.
• The date is invalid if it is not between 1 and 30 in the months of April, June, September, and November.
• The date is invalid if it is not between 1 and 31 for the months of January, March, April, May, July, August, October, and December.
• If the month is February, the day should be between 1 and 28 for non-leap years and between 1 and 29 for leap years.
• If the date is correct, it should be increased.
• The final incremented date is printed

### 2)By using if..elif..else Conditional StatementsÂ  and split() function(User Input)

Approach:

• Scan the date, month and year as int(input()).
• Separate the date by storing the day, month, and year in different variables.
• Check the validity of the day, month, and year using various if-statements.
• If the date is valid, increment it .
• Print the increment date.
• Exit of Program.

Below is the implementation:

# Scan the date, month and year as int(input()).
day = int(input("Enter some random day = "))
month = int(input("Enter some random month = "))
year = int(input("Enter some random year = "))
if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
maxdays = 31
elif(month == 4 or month == 6 or month == 9 or month == 11):
maxdays = 30
elif(year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
maxdays = 29
else:
maxdays = 28
if(month < 1 or month > 12):
print("The given date", given_date, "is not valid")
elif(day < 1 or day > maxdays):
print("The given date", given_date, "is not valid")
elif(day == maxdays and month != 12):
day = 1
month = month+1
print("The incremented given date is: ", day, month, year)
elif(day == 31 and month == 12):
day = 1
month = 1
year = year+1
print("The incremented given date is: ", day, '/', month, '/', year)
else:
day = day + 1
print("The incremented given date is: ",  day, '/', month, '/', year)


Output:

Enter some random day = 11
Enter some random month = 2
Enter some random year = 2001
The incremented given date is: 12 / 2 / 2001

Related Programs:

## Python Program to Form an Integer that has the Number of Digits at Tenâ€™s Place and the Least Significant Digit of the Entered Integer at Oneâ€™s Place

Given a number which is integer , the task is to create an integer with the number of digits at ten’s place and the least significant digit of the entered integer at one’s place.

Examples:

Example1:

Input:

given number = 37913749

Output:

The required number = 89

Example2:

Input:

 given number =78329942

Output:

The required number = 82

## Create an integer with the number of digits at ten’s place and the least significant digit of the entered integer at one’s place in Python

There are several ways to create an integer with the number of digits at ten’s place and the least significant digit of the entered integer at one’s place some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

### Method #1:Using while loop and String Conversion ( Static Input)

Approach:

• Give a number as static input and store it in a variable.
• Make a duplicate of the integer.
• Take a variable which stores the count of digits and initialize it with 0
• Using a while loop, calculate the number of digits in the givenÂ integer.
• Convert the integer copy and the number of digits count to string.
• Concatenate the integer’s last digit with the count.
• The newly created integer should be printed.
• Exit of program.

Below is the implementation:

# given number numb
numb = 37913749
# Taking a temporary variable which stores the given number
tempNum = numb
# Take a variable which stores the count of digits and initialize it with 0
countTotalDigits = 0
# looping till the given number is greater than 0
while(numb > 0):
# increasing the count of digits by 1
countTotalDigits = countTotalDigits+1
# Dividing the number by 10
numb = numb//10
# converting the temporary variable to string
strnum = str(tempNum)
# Extracting least significant digit
leastSigDigit = strnum[-1]
# converting the count Total Digits to string
countTotalDigits = str(countTotalDigits)
# calculating required number
resnum = countTotalDigits+leastSigDigit
print("The required number =", resnum)


Output:

The required number = 89

Explanation:

• Give a number as static input and store it in a variable.
• Because the original value of the variable would be modified for counting the number of digits, a copy of the variable is created.
• The while loop is employed, and the modulus operator is utilized to get the last digit of the number.
• The count value is incremented each time a digit is obtained.
• The variable’s number of digits and the number are transformed to string for simplicity of concatenation.
• The string’s final digit is then retrieved and concatenated to the count variable.
• The newly generated number is then printed.

### Method #2:Using while loop and String Conversion ( User Input)

Approach:

• Scan the given number using int(input()) and store it in a variable.
• Make a duplicate of the integer.
• Take a variable which stores the count of digits and initialize it with 0
• Using a while loop, calculate the number of digits in the givenÂ integer.
• Convert the integer copy and the number of digits count to string.
• Concatenate the integer’s last digit with the count .
• The newly created integer should be printed.
• Exit of program.

Below is the implementation:

# given number numb
numb = int(input("enter any number = "))
# Taking a temporary variable which stores the given number
tempNum = numb
# Take a variable which stores the count of digits and initialize it with 0
countTotalDigits = 0
# looping till the given number is greater than 0
while(numb > 0):
# increasing the count of digits by 1
countTotalDigits = countTotalDigits+1
# Dividing the number by 10
numb = numb//10
# converting the temporary variable to string
strnum = str(tempNum)
# Extracting least significant digit
leastSigDigit = strnum[-1]
# converting the count Total Digits to string
countTotalDigits = str(countTotalDigits)
# calculating required number
resnum = countTotalDigits+leastSigDigit
print("The required number =", resnum)


Output:

enter any number = 78329942
The required number = 82

### Method #3: Using len() and indexing by converting number to string (Static Input)

Approach:

• Give a number as static input and store it in a variable.
• Using the str() method, convert the given number to a string.
• Determine the number of digits in the given number by computing the length of the string with the len() function.
• Concatenate the integer’s last digit with the count.
• The newly created integer should be printed.
• Exit of program.

Below is the implementation:

# given number numb
numb = 82179
# Using the str() method, convert the given number to a string.
strnum = str(numb)

# Determine the number of digits in the given number by computing
# the length of the string with the len() function.
countTotalDigits = len(strnum)

# Extracting least significant digit
leastSigDigit = strnum[-1]
# converting the count Total Digits to string
countTotalDigits = str(countTotalDigits)
# calculating required number
resnum = countTotalDigits+leastSigDigit
print("The required number =", resnum)


Output:

The required number = 59

Related Programs:

## Python Program to Print all Numbers in a Range Divisible by a Given Number

Given three integers, the task is to print all values in the given range that are divisible by the third number, where the first number specifies the lower limit and the second number specifies the upper limit.

Examples:

Example1:

Input:

lower limit = 1
upper limit = 263
given number = 5

Output:

The numbers which are divisible by 5 from 17 to 263 are:
20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165
170 175 180 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260

Example2:

Input:

Enter the lower limit = 37
Enter the upper limit = 217
Enter the given number = 3

Output:

The numbers which are divisible by 3 from 37 to 217 are:
39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 102 105 108 111
114 117 120 123 126 129 132 135 138 141 144 147 150 153 156 159 162 165 168
171 174 177 180 183 186 189 192 195 198 201 204 207 210 213 216

Example3:

Input:

Enter the lower limit = 128
Enter the upper limit = 659
Enter the given number = 7

Output:

The numbers which are divisible by 7 from 128 to 659 are:
133 140 147 154 161 168 175 182 189 196 203 210 217 224 231 238 245 252 259 266 273 280 287 294 301 308
315 322 329 336 343 350 357 364 371 378 385 392 399 406 413 420 427 434 441 448 455 462 469 476 483 490
497 504 511 518 525 532 539 546 553 560 567 574 581 588 595 602 609 616 623 630 637 644 651 658

## Program to Print all Numbers in a Range Divisible by a Given Number in Python

There are several ways to print all the numbers in the given range which are divisible by the given number some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

### Method #1:Using for loop(Static Input)

Approach:

• Give three numbers as static input.
• Using for loop, loop from lower limit to upper limit.
• Using an if conditional statement, determine whether the iterator value is divisible by the given number.
• If it is divisible then print the iterator value.
• Exit of program

Below is the implementation:

# given lower limit
lower_limit = 17
# given upper limit
upper_limit = 263
# given number
numb = 5
print("The numbers which are divisible by", numb,
"from", lower_limit, "to", upper_limit, "are:")
# Using for loop, loop from lower limit to upper limit
for val in range(lower_limit, upper_limit):
# Using an if conditional statement, determine whether
# the iterator value is divisible by the given number.
if(val % numb == 0):
print(val, end=" ")


Output:

The numbers which are divisible by 5 from 17 to 263 are:
20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175 180 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260

### Method #2:Using for loop(User Input)

Approach:

• Scan the lower limit, upper limit and the given number using int(input()).
• Using for loop, loop from lower limit to upper limit.
• Using an if conditional statement, determine whether the iterator value is divisible by the given number.
• If it is divisible then print the iterator value.
• Exit of program

Below is the implementation:

# Scanning the lower limit
lower_limit = int(input("Enter the lower limit = "))
# Scanning the upper limit
upper_limit = int(input("Enter the upper limit = "))
# Scanning the given number
numb = int(input("Enter the given number = "))
print("The numbers which are divisible by", numb,
"from", lower_limit, "to", upper_limit, "are:")
# Using for loop, loop from lower limit to upper limit
for val in range(lower_limit, upper_limit):
# Using an if conditional statement, determine whether
# the iterator value is divisible by the given number.
if(val % numb == 0):
print(val, end=" ")


Output:

Enter the lower limit = 37
Enter the upper limit = 217
Enter the given number = 3
The numbers which are divisible by 3 from 37 to 217 are:
39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 102 105 108 111 114 117 120 123 126 129 132 135 138 141 144 147 150 153 156 159 162 165 168 171 174 177 180 183 186 189 192 195 198 201 204 207 210 213 216

Explanation:

• The user must enter the upper and lower range limits.
• The user is next required to provide the number to be divided from the user.
• The value of i is between the lower and upper bounds.
• Whenever the remainder of an integer divided by numb equals zero, the i is printed.

### Method #3:Using While loop (User Input)

Approach:

• Scan the lower limit, upper limit and the given number using int(input()).
• Take a variable tempo and initialize it with lower limit.
• Loop till tempo is less than upper limit using while loop.
• Using an if conditional statement, determine whether the tempo value is divisible by the given number.
• If it is divisible then print the iterator value.
• Increment the tempo by 1
• Exit of program

Below is the implementation:

# Scanning the lower limit
lower_limit = int(input("Enter the lower limit = "))
# Scanning the upper limit
upper_limit = int(input("Enter the upper limit = "))
# Scanning the given number
numb = int(input("Enter the given number = "))
# Take a variable tempo and initialize it with lower limit.
tempo = lower_limit
print("The numbers which are divisible by", numb,
"from", lower_limit, "to", upper_limit, "are:")
# Loop till tempo is less than upper limit using while loop.
while(tempo < upper_limit):
# Using an if conditional statement, determine whether
# the tempo value is divisible by the given number.
if(tempo % numb == 0):
print(tempo, end=" ")
# Increment the tempo by 1
tempo = tempo+1


Output:

Enter the lower limit = 128
Enter the upper limit = 659
Enter the given number = 7
The numbers which are divisible by 7 from 128 to 659 are:
133 140 147 154 161 168 175 182 189 196 203 210 217 224 231 238 245 252 259 266 273 280 287 294 301 308 315 322 329 336 343 350 357 364 371 378 385 392 399 406 413 420 427 434 441 448 455 462 469 476 483 490 497 504 511 518 525 532 539 546 553 560 567 574 581 588 595 602 609 616 623 630 637 644 651 658

Related Programs:

## Program to Print Collatz Conjecture for a Given Number in C++ and Python

In the previous article, we have discussed about Program to Read a Number n and Compute n+nn+nnn in C++ and Python. Let us learn Program to Print Collatz Conjecture for a Given Number in C++ Program.

Given a number , the task is to print Collatz Conjecture of the given number in C++ and Python.

Collatz Conjecture:

• The Collatz Conjecture states that a specific sequence will always reach the value 1.
• It is given as follows, beginning with some integer n:
• If n is an even number, the following number in the sequence is n/2.
• Otherwise, the following number is 3n+1 (if n is odd).

Examples:

Example1:

Input:

given number =5425

Output:

The Collatz Conjecture of the number :
5425 16276 8138 4069 12208 6104 3052 1526 763 2290 1145 3436 1718 859 2578 1289 3868 1934 967 2902 1451 4354 2177 6532 3266 1633 4900 2450 1225 3676 1838 919 2758 1379 4138 2069 6208 3104 1552 776 388 194 97 292 146 73 220 110 55 166 83 250 125 376 188 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2  1

Example2:

Input:

given number=847

Output:

The Collatz Conjecture of the number :
847 2542 1271 3814 1907 5722 2861 8584 4292 2146 1073 3220 1610 805 2416 1208 604 302 151 454 227 682 341 1024 512 256 128 64 32 16 8 4 2  1

## Program to Print Collatz Conjecture for a Given Number in C++ and Python

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

### 1)Printing Collatz Conjecture sequence of the given number in Python

Approach:

• Scan the given number or give number as static input.
• Iterate till the given number is not equal to 1 using while loop.
• Print the number numb.
• If the number is even then set n to n/2.
• If the number is odd then setÂ  n to 3*n+1.
• Print 1 after end of while loop.
• The Exit of the Program.

Below is the implementation:

# function which prints collatz sequence of the given number
def printCollatz(numb):
# Iterate till the given number is not equal to 1 using while loop.
while numb > 1:
# Print the number numb
print(numb, end=' ')
# If the number is even then set n to n/2.
if (numb % 2 == 0):
numb = numb//2
# If the number is odd then setÂ  n to 3*n+1.
else:
numb = 3*numb + 1
# Print 1 after end of while loop.
print(1, end='')

# given number
numb = 179
print('The Collatz Conjecture of the number :')
# passing the given numb to printCollatz function to
# print collatzConjecture sequence of the given number
printCollatz(numb)


Output:

The Collatz Conjecture of the number :
179 538 269 808 404 202 101 304 152 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

### 2)Printing Collatz Conjecture sequence of the given number in C++

Approach:

• Scan the given number using cin or give number as static input
• Iterate till the given number is not equal to 1 using while loop.
• Print the number numb.
• If the number is even then set n to n/2.
• If the number is odd then setÂ  n to 3*n+1.
• Print 1 after end of while loop.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
// function which prints collatz sequence of the given
// number
void printCollatz(int numb)
{

// Iterate till the given number is not equal to 1 using
// while loop.
while (numb > 1) {
// Print the number numb
cout << numb << " ";
// the number is even then set n to n / 2.
if (numb % 2 == 0) {
numb = numb / 2;
}
// the number is odd then setÂ  n to 3 * n + 1.
else {
numb = 3 * numb + 1;
}
}
// Print 1 after end of while loop.
cout << " 1";
}
int main()
{

// given number
int numb = 179;
cout << "The Collatz Conjecture of the number :"
<< endl;
// passing the given numb to printCollatz function to
// print collatzConjecture sequence of the given number
printCollatz(numb);
return 0;
}

Output:

The Collatz Conjecture of the number :
179 538 269 808 404 202 101 304 152 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2  1

Related Programs:

## Python Program to Sort a List According to the Length of the Elements

List in Python :

The list data type is one of the most often used data types in Python. The square brackets [ ] easily identify a Python List. Lists are used to store data items, with each item separated by a comma (,). A Python List can include data elements of any data type, including integers and Booleans.

One of the primary reasons that lists are so popular is that they are mutable. Any data item in a List can be replaced by any other data item if it is mutable. This distinguishes Lists from Tuples, which are likewise used to store data elements but are immutable.

Given a list, the task is to sort the list according to the length of the elements in the given list

Example:

Input:

given list = ["hello", "this", "is", "BTechGeeks", "online", "platform", "for", "Python", "and", "many", "Programming", "languages"]

Output:

printing the given list before sorting according to length :
['hello', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'Python', 'and', 'many', 'Programming', 'languages']
printing the given list after sorting according to length :
['is', 'for', 'and', 'this', 'many', 'hello', 'online', 'Python', 'platform', 'languages', 'BTechGeeks', 'Programming']

## Python Program to Sort a List According to the Length of the Elements

There are several ways to sort the given list according to the length of the elements some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

### Method #1:Using sort function ( Static Input )

Approach:

• Give the list input as static
• Then use sort() function to sort the given list
• Pass key=len as parameters to the sort function as we have to sort the list according to the length of elements.
• print the list

Below is the implementation:

def lengthSort(given_list):
# sorting the given list by length of elements of the given list
given_list.sort(key=len)
# return the list
return given_list

# given list
given_list = ["hello", "this", "is", "BTechGeeks", "online", "platform",
"for", "Python", "and", "many", "Programming", "languages"]
# printing the given list before sorting according to length
print("printing the given list before sorting according to length : ")
print(given_list)
# passing the given_list to lengthSort function to sort
# the list according to the length of the elements of the given list
# printing the given list before sorting according to length
print("printing the given list after sorting according to length : ")
print(lengthSort(given_list))


Output:

printing the given list before sorting according to length :
['hello', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'Python', 'and', 'many', 'Programming', 'languages']
printing the given list after sorting according to length :
['is', 'for', 'and', 'this', 'many', 'hello', 'online', 'Python', 'platform', 'languages', 'BTechGeeks', 'Programming']

### Method #2:Using sort function ( User Input )

Approach:

• Scan the list as string and convert it to list of strings using split() function.
• Then use sort() function to sort the given list
• Pass key=len as parameters to the sort function as we have to sort the list according to the length of elements.
• print the list

Below is the implementation:

def lengthSort(given_list):
# sorting the given list by length of elements of the given list
given_list.sort(key=len)
# return the list
return given_list

# given list
given_list = list(
input("Enter the elements of the given list separated by spaces = ").split())
# printing the given list before sorting according to length
print("printing the given list before sorting according to length : ")
print(given_list)
# passing the given_list to lengthSort function to sort
# the list according to the length of the elements of the given list
# printing the given list before sorting according to length
print("printing the given list after sorting according to length : ")
print(lengthSort(given_list))


Output:

Enter the elements of the given list separated by spaces =hello this is BTechGeeks online platform for Python and many Programming languages
printing the given list before sorting according to length :
['hello', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'Python', 'and', 'many', 'Programming', 'languages']
printing the given list after sorting according to length :
['is', 'for', 'and', 'this', 'many', 'hello', 'online', 'Python', 'platform', 'languages', 'BTechGeeks', 'Programming']

### Method #3:Using sorted function ( Static Input )

Approach:

• Give the list input as static
• Then use sort() function to sort the given list
• Pass given list andÂ  key=len as parameters to the sorted() function as we have to sort the list according to the length of elements.
• print the list

Below is the implementation:

def lengthSort(given_list):
# sorting the given list by length of elements of the given list
given_list = sorted(given_list, key=len)
# return the list
return given_list

# given list
given_list = ["hello", "this", "is", "BTechGeeks", "online", "platform",
"for", "Python", "and", "many", "Programming", "languages"]
# printing the given list before sorting according to length
print("printing the given list before sorting according to length : ")
print(given_list)
# passing the given_list to lengthSort function to sort
# the list according to the length of the elements of the given list
# printing the given list before sorting according to length
print("printing the given list after sorting according to length : ")
print(lengthSort(given_list))


Output:

printing the given list before sorting according to length :
['hello', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'Python', 'and', 'many', 'Programming', 'languages']
printing the given list after sorting according to length :
['is', 'for', 'and', 'this', 'many', 'hello', 'online', 'Python', 'platform', 'languages', 'BTechGeeks', 'Programming']

### Method #4:Using sorted function ( User Input )

Approach:

• Scan the list as string and convert it to list of strings using split() function.
• Then use sorted() function to sort the given list
• Pass given list andÂ  key=len as parameters to the sorted()Â  function as we have to sort the list according to the length of elements.
• print the list

Below is the implementation:

def lengthSort(given_list):
# sorting the given list by length of elements of the given list
given_list = sorted(given_list, key=len)
# return the list
return given_list

# given list
given_list = list(
input("Enter the elements of the given list separated by spaces").split())
# printing the given list before sorting according to length
print("printing the given list before sorting according to length : ")
print(given_list)
# passing the given_list to lengthSort function to sort
# the list according to the length of the elements of the given list
# printing the given list before sorting according to length
print("printing the given list after sorting according to length : ")
print(lengthSort(given_list))


Output:

Enter the elements of the given list separated by spaces =hello this is BTechGeeks online platform for Python and many Programming languages
printing the given list before sorting according to length :
['hello', 'this', 'is', 'BTechGeeks', 'online', 'platform', 'for', 'Python', 'and', 'many', 'Programming', 'languages']
printing the given list after sorting according to length :
['is', 'for', 'and', 'this', 'many', 'hello', 'online', 'Python', 'platform', 'languages', 'BTechGeeks', 'Programming']

Related Programs: