Python

Program to Add Number to each Element in a List

Python Program to Add Number to each Element in a List

In the previous article, we have discussed Python Program to Check a Binary Number is Divisible by a number N.
Given a list and the task is to add a given input number to each element in a list.

Examples:

Example1:

Input:

Given list = [2, 4, 6, 8, 10]
Given number = 5

Output:

The given list after addition of a number to each element in a list =  [7, 9, 11, 13, 15]

Example2:

Input:

Given list = [1, 4, 6, 2, 9]
Given number = 10

Output:

The given list after addition of a number to each element in a list = [11, 14, 16, 12, 19]

Program to Add Number to each Element in a List

Below are the ways to add a given input number to each element in a list.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the List as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Loop in the above-given list using the for loop.
  • Inside the loop, Increment the iterator value of the list by the given number and store it in the same variable
  • Print the given list after the addition of a given number to each element in a list.
  • The Exit of the program.

Below is the implementation:

# Give the List as static input and store it in a variable.
gven_lst = [2,4,6,8,10]
# Give the number as static input and store it in another variable.
numbr = 5
# Calculate the length of the given list using len() function and store it
# in another variable.
len_lst = len(gven_lst)
# Loop in the above-given list using the for loop.
for i in range(len_lst):
  # Inside the loop, Increment the iterator value of the list by the given number
  # and store it in the same variable
    gven_lst[i] = gven_lst[i]+numbr
# Print the given list after the addition of a given number to each element in a list .
print("The given list after addition of a number to each element in a list = ", gven_lst)

Output:

The given list after addition of a number to each element in a list =  [7, 9, 11, 13, 15]

Method #2: Using For Loop (User Input)

Approach:

  • Give the List as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Give the number as user input using the int(input()) function and store it in another variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Loop in the above-given list using the for loop.
  • Inside the loop, Increment the iterator value of the list by the given number and store it in the same variable
  • Print the given list after the addition of a given number to each element in a list.
  • The Exit of the program.

Below is the implementation:

# Give the List as user input using list(),map(),input(),and split() functions and 
#store it in a variable.
gven_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the number as user input using the int(input()) function and 
#store it in another variable.
numbr = int(input('Enter some random number = '))
# Calculate the length of the given list using len() function and store it
# in another variable.
len_lst = len(gven_lst)
# Loop in the above-given list using the for loop.
for i in range(len_lst):
  # Inside the loop, Increment the iterator value of the list by the given number
  # and store it in the same variable
    gven_lst[i] = gven_lst[i]+numbr
# Print the given list after the addition of a given number to each element in a list .
print("The given list after addition of a number to each element in a list = ", gven_lst)

Output:

Enter some random List Elements separated by spaces = 1 4 6 2 9
Enter some random number = 10
The given list after addition of a number to each element in a list = [11, 14, 16, 12, 19]

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.

Python Program to Add Number to each Element in a List Read More »

Program to Print Largest Even and Largest Odd Number in a List

Python Program to Print Largest Even and Largest Odd Number in a List

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

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 print the largest Even and Largest Odd number in the given list in Python

Examples:

Example1:

Input:

given list =[12, 21, 45, 146, 197, 4]

Output:

The Largest even number in the given list [12, 21, 45, 146, 197, 4] = 146
The Largest odd number in the given list [12, 21, 45, 146, 197, 4] = 197

Example2:

Input:

given list =  [532, 234, 9273, 845, 1023, 9]

Output:

The Largest even number in the given list [532, 234, 9273, 845, 1023, 9] = 532
The Largest odd number in the given list [532, 234, 9273, 845, 1023, 9] = 9273

Program to Print Largest Even and Largest Odd Number in a List in Python

Below are the ways to print the largest even element and largest odd element in the given list :

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() and Conditional Statements(User Input)

Approach:

  • Take the user’s input on the number of elements to include in the list.
  •  Using a for loop, Scan the elements from the user and append them to a list.
  • Using a for loop, retrieve the elements from the list one at a time, determine whether they are odd or even, and append them to various lists.
  • Sort both lists separately and calculate the length of each.
  • Output the final elements of the sorted lists.
  • Exit of Program

Below is the implementation:

# scanning the total number of elements of the given list
totalCount = int(
    input("Enter the total number of elements of the given list = "))
# Taking a empty list
given_list = []
# Using for loop to loop totalCount times
for i in range(totalCount):
    eleme = int(input("Enter some random element(integer) = "))
    given_list.append(eleme)
# Taking two empty lists which stores eeven and odd numbers
evenNumList = []
oddNumList = []
# Traversing the list using for loop
for eleme in given_list:
  # if the element is even then add this element to evenNumList using append() function
    if(eleme % 2 == 0):
        evenNumList.append(eleme)
  # if the element is even then add this element to oddNumList using append() function
    else:
        oddNumList.append(eleme)
# sorting evenNumList using sort() function
evenNumList.sort()
# sorting oddNumList using sort() function
oddNumList.sort()
print("The Largest even number in the given list",
      given_list, "=", evenNumList[-1])
print("The Largest odd number in the given list",
      given_list, "=", oddNumList[-1])

Output:

Enter the total number of elements of the given list = 6
Enter some random element(integer) = 12
Enter some random element(integer) = 21
Enter some random element(integer) = 45
Enter some random element(integer) = 146
Enter some random element(integer) = 197
Enter some random element(integer) = 4
The Largest even number in the given list [12, 21, 45, 146, 197, 4] = 146
The Largest odd number in the given list [12, 21, 45, 146, 197, 4] = 197

Method #2: Using sort() and Conditional Statements(Static Input)

Approach:

  • Give the elements of the list as static input
  • Using a for loop, retrieve the elements from the list one at a time, determine whether they are odd or even, and append them to various lists.
  • Sort both lists separately and calculate the length of each.
  • Output the final elements of the sorted lists.
  • Exit of Program

Below is the implementation:

# given list
given_list = [532, 234, 9273, 845, 1023, 9]
# Taking two empty lists which stores eeven and odd numbers
evenNumList = []
oddNumList = []
# Traversing the list using for loop
for eleme in given_list:
  # if the element is even then add this element to evenNumList using append() function
    if(eleme % 2 == 0):
        evenNumList.append(eleme)
  # if the element is even then add this element to oddNumList using append() function
    else:
        oddNumList.append(eleme)
# sorting evenNumList using sort() function
evenNumList.sort()
# sorting oddNumList using sort() function
oddNumList.sort()
print("The Largest even number in the given list",
      given_list, "=", evenNumList[-1])
print("The Largest odd number in the given list",
      given_list, "=", oddNumList[-1])

Output:

The Largest even number in the given list [532, 234, 9273, 845, 1023, 9] = 532
The Largest odd number in the given list [532, 234, 9273, 845, 1023, 9] = 9273

Method #3:Using sort and List Comprehension(Static Input)

Approach:

  • Give the elements of the list as static input
  • Take all even numbers and odd numbers of the given list into two separate lists using List Comprehension
  • Sort both lists separately and calculate the length of each.
  • Output the final elements of the sorted lists.
  • Exit of Program

Below is the implementation:

# given list
given_list = [532, 234, 9273, 845, 1023, 9]
# Take all even numbers and odd numbers of the given list into
# two separate lists using List Comprehension
evenNumList = [eleme for eleme in given_list if eleme % 2 == 0]
oddNumList = [eleme for eleme in given_list if eleme % 2 != 0]
# sorting evenNumList using sort() function
evenNumList.sort()
# sorting oddNumList using sort() function
oddNumList.sort()
print("The Largest even number in the given list",
      given_list, "=", evenNumList[-1])
print("The Largest odd number in the given list",
      given_list, "=", oddNumList[-1])

Method #4:Using sort and List Comprehension(User Input)

Approach:

  • Take the user’s input on the number of elements to include in the list.
  •  Using a for loop, Scan the elements from the user and append them to a list.
  • Take all even numbers and odd numbers of the given list into two separate lists using List Comprehension
  • Sort both lists separately and calculate the length of each.
  • Output the final elements of the sorted lists.
  • Exit of Program

Below is the implementation:

# scanning the total number of elements of the given list
totalCount = int(
    input("Enter the total number of elements of the given list = "))
# Taking a empty list
given_list = []
# Using for loop to loop totalCount times
for i in range(totalCount):
    eleme = int(input("Enter some random element(integer) = "))
    given_list.append(eleme)
# Take all even numbers and odd numbers of the given list into
# two separate lists using List Comprehension
evenNumList = [eleme for eleme in given_list if eleme % 2 == 0]
oddNumList = [eleme for eleme in given_list if eleme % 2 != 0]
# sorting evenNumList using sort() function
evenNumList.sort()
# sorting oddNumList using sort() function
oddNumList.sort()
print("The Largest even number in the given list",
      given_list, "=", evenNumList[-1])
print("The Largest odd number in the given list",
      given_list, "=", oddNumList[-1])

Output:

Enter the total number of elements of the given list = 5
Enter some random element(integer) = 234
Enter some random element(integer) = 122
Enter some random element(integer) = 65
Enter some random element(integer) = 19
Enter some random element(integer) = 102
The Largest even number in the given list [234, 122, 65, 19, 102] = 234
The Largest odd number in the given list [234, 122, 65, 19, 102] = 65

Related Programs:

Python Program to Print Largest Even and Largest Odd Number in a List Read More »

Python Program to Print all Twin Primes less than N

Python Program to Print all Twin Primes less than N

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Given a number N the task is to print all twin primes less than the given number in Python.

Twin Primes:

We know that Prime Numbers are those with exactly two Factors. 1 and the number itself are the two Factors.

Twin Primes are pairs of primes that differ by two digits.

(3, 5), (5, 7), (11, 13), and so on are some examples.

In the Number System, there is an unlimited number of Twin Primes.

Examples:

Example1:

Input:

Given number =562

Output:

The twin primes below the number 562 are :
(3,5)  (5,7)  (11,13)  (17,19)  (29,31)  (41,43)  (59,61)  (71,73)  (101,103)  (107,109)  (137,139)  (149,151)  (179,181)  
(191,193)  (197,199)  (227,229)  (239,241)  (269,271)  (281,283)  (311,313)  (347,349)  (419,421)  (431,433)  (461,463)
 (521,523)

Example2:

Input:

Given number =842

Output:

Enter some random number = 842
The twin primes below the number 842 are :
(3,5) (5,7) (11,13) (17,19) (29,31) (41,43) (59,61) (71,73) (101,103) (107,109) (137,139) (149,151) (179,181) (191,193)
 (197,199) (227,229) (239,241) (269,271) (281,283) (311,313) (347,349) (419,421) (431,433) (461,463) (521,523)
 (569,571) (599,601) (617,619) (641,643) (659,661) (809,811) (821,823) (827,829)

Python Program to Print all Twin Primes less than N

Below are the ways to print all Twin primes less than the given number N.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number N as static input and store it in a variable.
  • Let us define the function checkPrimeNum(), which accepts an integer as input and returns True if it is prime and False if it is not.
  • Declare the variable count and set it to zero. The count variable is used here to count the number of Factors of a Number. Whenever we find a factor for the given number, we will increment the value of the count.
  • If the count equals 2, the integer is prime, and the function is defined to return True.
  • Else it will return False.
  • Loop from 2 to the given number N using For loop.
  • If both checkPrimeNum(m) and checkPrimeNum(m+2) return True, print m and m+2 where m is the iterator value of the For loop.
  • The Exit of the Program.

Below is the implementation:

# Let us define the function checkPrimeNum(), which accepts an integer as input and
# returns True if it is prime and False if it is not.


def checkPrimeNum(gvnnum):
    # Declare the variable count and set it to zero.
    # The count variable is used here to count the number of Factors of a Number.
    # Whenever we find a factor for the given number,
    # we will increment the value of the count.
    countfactrs = 0
    for m in range(1, gvnnum+1):
        if gvnnum % m == 0:
            countfactrs = countfactrs + 1
    # If the count equals 2, the integer is prime,
    # and the function is defined to return True.
    if countfactrs == 2:
        return True


# Give the number N as static input and store it in a variable.
numbr = 562
print('The twin primes below the number', numbr, 'are :')
# Loop from 2 to the given number N using For loop.
for m in range(2, numbr):
  # If both checkPrimeNum(m) and checkPrimeNum(m+2) return True,
  # print m and m+2 where m is the iterator value of the For loop.
    if (checkPrimeNum(m) == True and checkPrimeNum(m+2) == True):
        print('('+str(m)+','+str(m+2)+')', end='  ')

Output:

The twin primes below the number 562 are :
(3,5)  (5,7)  (11,13)  (17,19)  (29,31)  (41,43)  (59,61)  (71,73)  (101,103)  (107,109)  (137,139)  (149,151)  (179,181)  
(191,193)  (197,199)  (227,229)  (239,241)  (269,271)  (281,283)  (311,313)  (347,349)  (419,421)  (431,433)  (461,463)
 (521,523)

Method #2: Using For Loop (User Input)

Approach:

  • Give the number N as user input using int(input()) and store it in a variable.
  • Let us define the function checkPrimeNum(), which accepts an integer as input and returns True if it is prime and False if it is not.
  • Declare the variable count and set it to zero. The count variable is used here to count the number of Factors of a Number. Whenever we find a factor for the given number, we will increment the value of the count.
  • If the count equals 2, the integer is prime, and the function is defined to return True.
  • Else it will return False.
  • Loop from 2 to the given number N using For loop.
  • If both checkPrimeNum(m) and checkPrimeNum(m+2) return True, print m and m+2 where m is the iterator value of the For loop.
  • The Exit of the Program.

Below is the implementation:

# Let us define the function checkPrimeNum(), which accepts an integer as input and
# returns True if it is prime and False if it is not.


def checkPrimeNum(gvnnum):
    # Declare the variable count and set it to zero.
    # The count variable is used here to count the number of Factors of a Number.
    # Whenever we find a factor for the given number,
    # we will increment the value of the count.
    countfactrs = 0
    for m in range(1, gvnnum+1):
        if gvnnum % m == 0:
            countfactrs = countfactrs + 1
    # If the count equals 2, the integer is prime,
    # and the function is defined to return True.
    if countfactrs == 2:
        return True


# Give the number N as user input using int(input()) and store it in a variable.
numbr = int(input('Enter some random number = '))
print('The twin primes below the number', numbr, 'are :')
# Loop from 2 to the given number N using For loop.
for m in range(2, numbr):
  # If both checkPrimeNum(m) and checkPrimeNum(m+2) return True,
  # print m and m+2 where m is the iterator value of the For loop.
    if (checkPrimeNum(m) == True and checkPrimeNum(m+2) == True):
        print('('+str(m)+','+str(m+2)+')', end='  ')

Output:

Enter some random number = 842
The twin primes below the number 842 are :
(3,5) (5,7) (11,13) (17,19) (29,31) (41,43) (59,61) (71,73) (101,103) (107,109) (137,139) (149,151) (179,181) (191,193)
(197,199) (227,229) (239,241) (269,271) (281,283) (311,313) (347,349) (419,421) (431,433) (461,463) (521,523)
(569,571) (599,601) (617,619) (641,643) (659,661) (809,811) (821,823) (827,829)

Related Programs:

Python Program to Print all Twin Primes less than N Read More »

Program to Pick a Random Card

Python Program to Pick a Random Card

In the previous article, we have discussed Python Program to Print Non Square Numbers
Random Module in python :

As this Random module is one of Python’s predefined modules, its methods return random values.

It selects integers uniformly from a range. For sequences, it has a function to generate a random permutation of a list in-place, as well as a function to generate a random sampling without replacement. Let’s take a look at how to import the Random Module.

The random module in Python is made up of various built-in Methods.

To pick a random card from a deck of cards in Python, you must first store all of the cards. Then select a card at random. However, there are 52 cards. I don’t think it’s a good idea to keep all of the cards in a list one by one.

So we’ll figure out a better way to do this.

  • First, make a list of all the card values (values range from 2 to A).
  • Next, make a list of the card signs. (Heart, Club, Spades, Diamond).

Examples:

Example1:

Input:

Given card _points = ['A', 'K', 'Q', 'J', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Given card_signs = ['Heart','CLUB','DIAMOND','SPADE']

Output:

The random card from a deck of cards =  ('9', 'CLUB')

Example2:

Input:

Given card _points = ['A', 'K', 'Q', 'J', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Given card_signs = ['heart ','club', 'spade', 'diamond']

Output:

The random card from a deck of cards =  ('J', 'Heart')

Program to Pick a random card

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Below are the ways to pick a random card from the deck of cards.

Method #1: Using random.choice Method (Static input)

Approach:

  • Import random module using the import keyword.
  • Give the first list of card values as static input and store it in a variable.
  • Give the second list of card signs as static input and store it in another variable.
  • Apply random. choice() method for the first list to get the random item and store it in another variable.
  • Apply random. choice() method for the second list to get the random item and store it in another variable.
  • Get the random card by assigning both obtained random cards and store it in another variable.
  • Print the random card from the deck of cards.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the first list of card values as static input say and store it in a variable.
card_points = ['A', 'K', 'Q', 'J', '2',
               '3', '4', '5', '6', '7', '8', '9', '10']
# Give the second list of card signs as static input and store it in another variable.
card_signs = ['Heart', 'CLUB', 'DIAMOND', 'SPADE']
# Apply random. choice() method for the first list to get the random item and
# store it in another variable.
randm_card = random.choice(card_points)
# Apply random. choice() method for the second list to get the random item and
# store it in another variable.
randm_sign = random.choice(card_signs)
# Get the random card by assigning both obtained random cards and store it in
# another variable.
rndm_crd = randm_card, randm_sign
# Print the random card from the deck of cards.
print("The random card from a deck of cards = ", rndm_crd)

Output:

The random card from a deck of cards =  ('9', 'CLUB')

Method #2: Using random.choice Method (User input)

Approach:

  • Import random module using the import keyword.
  • Give the first list of card values as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Give the second list of card signs as user input using list(),map(),input(),and split() functions and store it in another variable.
  • Apply random. choice() method for the first list to get the random item and store it in another variable.
  • Apply random. choice() method for the second list to get the random item and store it in another variable.
  • Get the random card by assigning both obtained random cards and store it in another variable.
  • Print the random card from the deck of cards.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the first list of card values as user input using list(),map(),input(),and split() functions 
#and store it in a variable.
card_points = list(map(str, input( 'Enter some random List Elements separated by spaces = ').split()))
# Give the second list of card signs as user input using list(),map(),input(),and split() functions
#and store it in another variable.
card_signs = list(map(str, input( 'Enter some random List Elements separated by spaces = ').split()))
# Apply random. choice() method for the first list to get the random item and
# store it in another variable.
randm_card = random.choice(card_points)
# Apply random. choice() method for the second list to get the random item and
# store it in another variable.
randm_sign = random.choice(card_signs)
# Get the random card by assigning both obtained random cards and store it in
# another variable.
rndm_crd = randm_card, randm_sign
# Print the random card from the deck of cards.
print("The random card from a deck of cards = ", rndm_crd)

Output:

Enter some random List Elements separated by spaces = A K Q J 2 3 4 5 6 7 8 9 10
Enter some random List Elements separated by spaces = heart club spade diamond
The random card from a deck of cards = ('6', 'club')

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.

Python Program to Pick a Random Card Read More »

Program to Print a Deck of Cards in Python

Python Program to Print a Deck of Cards in Python

In the previous article, we have discussed Python Program to Calculate Age in Days from Date of Birth
A deck of cards contains 52 cards.

  • There are 4 sign cards –  ‘Heart’, ‘CLUB’, ‘DIAMOND’, ‘SPADE’
  • There are 13 value of cards – ‘A’,’K’,’Q’,’J’,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9′,’10’

These are the cards A of Heart, K of Heart, Q of Heart, and so forth. Then there’s A of Club, K of Club, Q of Club, and so on.

As a result, we will have four different sets of a card, with 13 cards in each set. (Because there are 13 different values for each sign’s card)

As a result, the total number of cards = 13*4 = 52

Given two lists of cards and the task is to print a deck of cards.

For Loop:

A for loop is used to iterate through a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This works more like an iterator method in other object-oriented programming languages than for the keyword in other programming languages.

The for loop allows us to execute a set of statements once for each item in a list, tuple, set, and so on.

In General:

A deck of cards contains 52 cards.

Each card is divided into four suits, each of which contains 13 cards.

A deck of cards can also be classified as follows:

  1. Face cards
  2. Numbers (2 -10)
  3. Aces

These cards are also referred to as court cards.

In all four suits, they are Kings, Queens, and Jacks.

Program to Print a Deck of Cards in Python

Below are the ways to print a deck of cards.

Method: Using For Loop

Approach:

  • Give the list of value cards as static input and store it in a variable.
  • Give the list of signs cards as static input and store it in another variable.
  • Loop in the above list of value cards using the for loop and len() function.
  • Inside the loop, loop again in the above list of sign cards using the for loop and len() function.
  • Print the corresponding iterator values.
  • The Exit of the program.

Below is the implementation:

# Give the list of value cards as static input and store it in a variable.
card_values = ['A', 'K', 'Q', 'J', '2',
               '3', '4', '5', '6', '7', '8', '9', '10']
# Give the list of signs cards as static input and store it in another variable.
crd_signs = ['Heart', 'CLUB', 'DIAMOND', 'SPADE']
# Loop in the above list of value cards using the for loop and len() function.
print("The Deck of cards are:")
for val in range(len(card_values)):
    # Inside the loop, loop again in the above list of sign cards using the for loop
    # and len() function.
    for signval in range(len(crd_signs)):
     # Print the corresponding iterator values .
        print(card_values[val], crd_signs[signval])

Output:

A Heart
A CLUB
A DIAMOND
A SPADE
K Heart
K CLUB
K DIAMOND
K SPADE
Q Heart
Q CLUB
Q DIAMOND
Q SPADE
J Heart
J CLUB
J DIAMOND
J SPADE
2 Heart
2 CLUB
2 DIAMOND
2 SPADE
3 Heart
3 CLUB
3 DIAMOND
3 SPADE
4 Heart
4 CLUB
4 DIAMOND
4 SPADE
5 Heart
5 CLUB
5 DIAMOND
5 SPADE
6 Heart
6 CLUB
6 DIAMOND
6 SPADE
7 Heart
7 CLUB
7 DIAMOND
7 SPADE
8 Heart
8 CLUB
8 DIAMOND
8 SPADE
9 Heart
9 CLUB
9 DIAMOND
9 SPADE
10 Heart
10 CLUB
10 DIAMOND
10 SPADE

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.

Python Program to Print a Deck of Cards in Python Read More »

Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

Python Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

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 print the sum of all positive even numbers ,odd numbers and negative numbers in the given list in python.

Examples:

Example1:

Input:

given list =[23, 128, -4, -19, 233, 726, 198, 199, 203, -13]

Output:

The sum of all positive even numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 1052
The sum of all positive odd numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 658
The sum of all positive negative numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = -36

Example2:

Input:

given list =[-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]

Output:

The sum of all positive even numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]  = 444 
The sum of all positive odd numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  210 
The sum of all positive negative numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  -36

Python Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

Below are the ways to print the sum of all positive even numbers ,odd numbers and negative numbers in the given list 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.

Method #1:Using append() and Conditional Statements (User Input separated by newline)

Approach:

  • Take the user’s input on the number of elements to include in the list.
  •  Using a for loop, Scan the elements from the user and append them to a list.
  • Using a for loop, retrieve the elements from the list one at a time, determine whether they are positive odd, positive even or negative numbers and append them to various lists say posEven, posOdd ,negNum.
  • Calculate the sum of posEven, posOdd ,negNum and print them
  • Exit of program

Below is the implementation:

# scanning the total number of elements of the given list
totalCount = int(
    input("Enter the total number of elements of the given list = "))
# Taking a empty list
given_list = []
# Using for loop to loop totalCount times
for i in range(totalCount):
    eleme = int(input("Enter some random element(integer) = "))
    given_list.append(eleme)
# Taking three empty lists which stores positive
# ven numbers ,positive odd numbers and negative numbers
posEven = []
posOdd = []
negNum = []
# Traversing the list using for loop
for element in given_list:
    # checking if the number is greater than 0
    if(element > 0):
        # if the element is even then add this element to posEven using append() function
        if(element % 2 == 0):
            posEven.append(element)
    # if the element is even then add this element to posOdd using append() function
        else:
            posOdd.append(element)
    # else if the number is less than 0 then add to negNum list using append() function
    else:
        negNum.append(element)
        

# Calculating sum
posEvensum = sum(posEven)
posOddsum = sum(posOdd)
negNumsum = sum(negNum)
# printing the respectve sum's
print("The sum of all positive even numbers in thee given list = ",
      given_list, posEvensum)
print("The sum of all positive odd numbers in thee given list = ", given_list, posOddsum)
print("The sum of all positive negative numbers in thee given list = ",
      given_list, negNumsum)

Output:

Enter the total number of elements of the given list = 10
Enter some random element(integer) = -4
Enter some random element(integer) = 23
Enter some random element(integer) = 12
Enter some random element(integer) = -13
Enter some random element(integer) = 234
Enter some random element(integer) = 198
Enter some random element(integer) = 55
Enter some random element(integer) = -19
Enter some random element(integer) = 87
Enter some random element(integer) = 45
The sum of all positive even numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]  = 444
The sum of all positive odd numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  210
The sum of all positive negative numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  -36

Method #2:Using append() and Conditional Statements (Static Input separated by spaces)

Approach:

  • Given the input of the list as static.
  • Using a for loop, retrieve the elements from the list one at a time, determine whether they are positive odd, positive even or negative numbers and append them to various lists say posEven, posOdd ,negNum.
  • Calculate the sum of posEven, posOdd ,negNum and print them
  • Exit of program

Below is the implementation:

# given list
given_list = [23, 128, -4, -19, 233, 726, 198, 199, 203, -13]
# Taking three empty lists which stores positive
# even numbers ,positive odd numbers and negative numbers
posEven = []
posOdd = []
negNum = []
# Traversing the list using for loop
for element in given_list:
    # checking if the number is greater than 0
    if(element > 0):
        # if the element is even then add this element to posEven using append() function
        if(element % 2 == 0):
            posEven.append(element)
    # if the element is even then add this element to posOdd using append() function
        else:
            posOdd.append(element)
    # else if the number is less than 0 then add to negNum list using append() function
    else:
        negNum.append(element)


# Calculating sum
posEvensum = sum(posEven)
posOddsum = sum(posOdd)
negNumsum = sum(negNum)
# printing the respectve sum's
print("The sum of all positive even numbers in thee given list ",
      given_list, "=", posEvensum)
print("The sum of all positive odd numbers in thee given list ",
      given_list, "=", posOddsum)
print("The sum of all positive negative numbers in thee given list ",
      given_list, "=", negNumsum)

Output:

The sum of all positive even numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 1052
The sum of all positive odd numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 658
The sum of all positive negative numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = -36

Related Programs:

Python Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List Read More »

Program to Compute Simple Interest in Python

Python Program to Compute Simple Interest

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Simple Interest:

Simple interest (S.I) is the way by which the interest amount is calculated for a capital amount. If your pocket money is exhausted, did you ever borrow your siblings? Or perhaps lent him? When you borrow money, what happens? You utilize this money first and foremost for the purpose you borrowed. Afterwards, when you get your parents’ pocket money the next month, you give the money back. That’s how to borrow and lend at home.

But in the real world, money is not free to borrow. You typically have to borrow money from banks in the form of a loan. You paid a certain amount of money during paybacks, apart from the amount of the loan, depending both on the lending amount and on the lending time. Simple interest is called this. This word is often used in the banking industry.

Given all the required values like amount ,rate and time the task is to calculate the simple interest for the given values in Python

Examples:

Example1:

Input:

given amount=18816

given time= 3

given rate= 8.43

Output:

Example2:

Input:

given amount=49332

given time=3.4

given rate=6.732

Output:

The simple interest for the amount 49332 in 3.4 at the rate 6.732 % = 11291.502815999998

Program to Compute Simple Interest in Python

We can calculate simple interest easily using 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.

Formula for simple interest is given by:

SimpleInterest = (P x T x R) / 100

where

P= Principal Amount(given amount in this case)

T = Time Period (given time in this case)

R = Rate of interest( given rate in this case)

The primary complexity is the user’s input, since the values can be either decimal (float) or integer.

Method #1: Calculating Simple interest  (Static Input)

Approach:

  • Enter the values as static for  amount, rate and time
  • Calculate the simple interest using the formula.
  • Print the calculated simple interest value.
  • exit of program

Below is the implementation:

# given amount
given_amount = 18816
# given time in years
given_time = 3
# given rate of interest
given_rate = 8.43
# calculating simpleInterest using formula
simpleInt = (given_amount*given_time*given_rate)/100
# printing the simpleInterest of the above values
print("The simple interest for the amount", given_amount, "in",
      given_time, "at the rate", given_rate, "% =", simpleInt)

Output:

The simple interest for the amount 18816 in 3 at the rate 8.43 % = 4758.5664

Explanation:

  • User will enter the static values
  • For calculating a simple interest, the formula (amount*time*rate):/100 is used.
  • The simple  interest is printed subsequently.

Method #2: Calculating Simple interest (User Input)

Approach:

The application will request that the user first enter all three values. The input values of the user are floating. We can also utilize entities, although integer types are unlikely to always hold the main amount, time and interest. Then the simple interest will be calculated using the above formula and the result is printed.

Below is the implementation:

# given amount
given_amount = float(input("Enter the amount of which you want to calculate simple interest ="))
# given time in years
given_time=float(input("Enter the time of which you want to calculate simple interest = "))
# given rate of interest
given_rate=float(input("Enter the rate of interest of which you want to calculate simple interest = "))
# calculating simpleInterest using formula
simpleInt=(given_amount*given_time*given_rate)/100
# printing the simpleInterest of the above values
print("The simple interest for the amount", given_amount, "in",
      given_time, "at the rate", given_rate, "% =", simpleInt)

Output:

Enter the amount of which you want to calculate simple interest =39929
Enter the time of which you want to calculate simple interest = 7.5
Enter the rate of interest of which you want to calculate simple interest = 3.24
The simple interest for the amount 399299.0 in 7.5 at the rate 3.24 % = 97029.657

Explanation:

Take the user input for the amount, time and rate of interest for calculation of the simple interest in years. We read

the data with the input() method and then use float() to convert it to a floating point number. The method input()

reads the input of the user as a string. Therefore, initially we must convert it to float.

For calculating a simple interest, the formula (amount*time*rate):/100 is used.

Related Programs:

Python Program to Compute Simple Interest Read More »

Program to Multiply each Element of a List by a Number

Python Program to Multiply Each Element of a List by a Number | How to Multiply Each Element in a List by a Number in Python?

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Multiplying each element of a list will create a new list with each value from the original list multiplied by the number specified. In this tutorial, we have explained the different methods on how to multiply each element of the list by a number in python using for loops, numpy array, list comprehension, etc. Learn the Multiplication of All Elements of a List Process by having a quick glance at the sample python programs provided below.

Multiply Each Element of a List by a Number in Python Examples

Given a list and a number the task is to multiply each element of the given list by the given number in Python.

Example 1:

Input:

Given list = [12, 9, 4, 1, 47, 28, 19, 45, 9, 1, 4, 2, 5]
Given element =6

Output:

The original list is [12, 9, 4, 1, 47, 28, 19, 45, 9, 1, 4, 2, 5]
The given list after multiplying with 6 is:
[72, 54, 24, 6, 282, 168, 114, 270, 54, 6, 24, 12, 30]

Example 2:

Input:

Given list = [7, 1, 45, 88, 12, 65, 2, 3, 9, 7]
Given element =10

Output:

The original list is [7, 1, 45, 88, 12, 65, 2, 3, 9, 7]
The given list after multiplying with 10 is:
[70, 10, 450, 880, 120, 650, 20, 30, 90, 70]

How to Multiply Each Element in a List by a Number in Python?

Below are the ways to multiply each element of the given list by the given number in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Calculate the length of the list using the len() function and store it in a variable.
  • Loop till the length of the list using For loop.
  • Inside the For, loop multiply the list element with the given number.
  • Print the modified list.
  • The Exit of the Program.

Below is the implementation:

Python Program to Print Multiply each Element of a List by a Number using For Loop

# Give the list as static input and store it in a variable.
gvnlst = [12, 9, 4, 1, 47, 28, 19, 45, 9, 1, 4, 2, 5]
print('The original list is', gvnlst)
# Give the number as static input and store it in another variable.
numb = 6
# Calculate the length of the list using the len() function
# and store it in a variable.
lstlengt = len(gvnlst)
# Loop till the length of the list using For loop.
for m in range(lstlengt):
    # Inside the For, loop multiply the list element with the given number.
    gvnlst[m] = gvnlst[m]*numb
# Print the modified list.
print('The given list after multiplying with', numb, 'is:')
print(gvnlst)

Output:

The original list is [12, 9, 4, 1, 47, 28, 19, 45, 9, 1, 4, 2, 5]
The given list after multiplying with 6 is:
[72, 54, 24, 6, 282, 168, 114, 270, 54, 6, 24, 12, 30]

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the number as user input using int(input()) and store it in another variable.
  • Calculate the length of the list using the len() function and store it in a variable.
  • Loop till the length of the list using For loop.
  • Inside the For, loop multiply the list element with the given number.
  • Print the modified list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the number as user input using int(input()) and store it in another variable.
numb = int(input('Enter some random number = '))
# Calculate the length of the list using the len() function
# and store it in a variable.
lstlengt = len(gvnlst)
# Loop till the length of the list using For loop.
for m in range(lstlengt):
    # Inside the For, loop multiply the list element with the given number.
    gvnlst[m] = gvnlst[m]*numb
# Print the modified list.
print('The given list after multiplying with', numb, 'is:')
print(gvnlst)

Output:

Enter some random List Elements separated by spaces = 4 85 11 1 9 45 35 16 25 46 72 36 8 5 3 7
Enter some random number = 4
The given list after multiplying with 4 is:
[16, 340, 44, 4, 36, 180, 140, 64, 100, 184, 288, 144, 32, 20, 12, 28]

Method #3: Using List Comprehension (Static Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the number as user input using int(input()) and store it in another variable.
  • Multiply the given number with each list element using list comprehension.
  • Print the modified list.
  • The Exit of the Program.

Below is the implementation:

Python Program to Print Multiply Each Element of a List by a Number using List Comprehension

# Give the list as static input and store it in a variable.
gvnlst = [12, 9, 4, 1, 47, 28, 19, 45, 9, 1, 4, 2, 5]
print('The original list is', gvnlst)
# Give the number as static input and store it in another variable.
numb = 6
# Multiply the given number with each list element using list comprehension.
modifiedlst = [elemt*numb for elemt in gvnlst]
# Print the modified list.
print('The given list after multiplying with', numb, 'is:')
print(modifiedlst)

Output:

The original list is [12, 9, 4, 1, 47, 28, 19, 45, 9, 1, 4, 2, 5]
The given list after multiplying with 6 is:
[72, 54, 24, 6, 282, 168, 114, 270, 54, 6, 24, 12, 30]

Method #4: Using List Comprehension (User Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Multiply the given number with each list element using list comprehension.
  • Print the modified list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlist = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the number as user input using int(input()) and store it in another variable.
numb = int(input('Enter some random number = '))
# Multiply the given number with each list element using list comprehension.
modifiedlst = [elemt*numb for elemt in gvnlist]
# Print the modified list.
print('The given list after multiplying with', numb, 'is:')
print(modifiedlst)

Output:

Enter some random List Elements separated by spaces = 4 15 19 85 36 15 25 45 39 75 82 6 4 7 9 11
Enter some random number = 10
The given list after multiplying with 10 is:
[40, 150, 190, 850, 360, 150, 250, 450, 390, 750, 820, 60, 40, 70, 90, 110]

Multiply all Elements in a List using Numpy Array

We can use Numpy Library to multiply all the elements in a list by a number as follows

import numpy

numbers = range(10)
numpy_array = numpy.array(numbers)
new_array = numpy_array * 2

print(new_array)

Related Programs:

Python Program to Multiply Each Element of a List by a Number | How to Multiply Each Element in a List by a Number in Python? Read More »

Program to Enter Basic Salary and Calculate Gross Salary of an Employee

Python Program to Enter Basic Salary and Calculate Gross Salary of an Employee

In the previous article, we have discussed Python Program to Check Duck Number
Gross Salary:

It denotes the amount paid out to an individual prior to any voluntary or mandatory deductions. As a result, it is the total pay received by an employee before taxes and other deductions. Gross salary includes all sources of income and is not limited to only cash income. As a result, it includes any benefits or services received by an employee. The salary that an employee receives, on the other hand, is the net salary after deductions.

House rent allowance (HRA):

House rent allowance, or HRA, is a salary component that covers employees’ housing expenses.

Formula to calculate the Gross Salary :

Gross salary equals the sum of the basic salary plus the HRA and any other allowances.

Gross salary = Basic salary + House Rent Allowance + Other Allowances

Gross salary =basic + da + hr + da_on_ta

da=(15*basic)/100

hr=(10*basic)/100

da on ta=(3*basic)/100

Examples:

Example1:

Input:

Given Basic salary = 23000

Output:

The Employee's Gross salary from the given basic salary { 23000 } = 29440.0

Example2:

Input:

Given Basic salary = 18000

Output:

The Employee's Gross salary from the given basic salary { 18000 } = 23040.0

Program to Enter Basic Salary and Calculate Gross Salary of an Employee  in Python

Below are the ways to calculate the Gross salary from the given basic salary :

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the basic salary as static input and store it in a variable.
  • Calculate the value of da from the above given mathematical formula and store it in another variable.
  • Calculate the value of hr from the above given mathematical formula and store it in another variable.
  • Calculate the value of da-on-ta from the above given mathematical formula and store it in another variable.
  • Calculate the gross salary using the above given mathematical formula and store it in another variable.
  • Print the Gross salary of an employee from the given basic salary.
  • The Exit of the program.

Below is the implementation of the above given approach:

# Give the basic salary as static input and store it in a variable.
gvn_basc_sal = 23000
# Calculate the value of da from the above given mathematical formula and store
# it in another variable.
gvn_da = (float)(15 * gvn_basc_sal) / 100.0
# Calculate the value of hr from the above given mathematical formula and store
# it in another variable.
gvn_hr = (float)(10 * gvn_basc_sal) / 100.0
# Calculate the value of da-on-ta from the above given mathematical formula and store
# it in another variable.
gvn_da_on_ta = (float)(3 * gvn_basc_sal) / 100.0
# Calculate the gross salary using the above given mathematical formula and store
# it in another variable.
gros_sal = gvn_basc_sal + gvn_da + gvn_hr + gvn_da_on_ta
# Print the Gross salary of an employee from the given basic salary.
print(
    "The Employee's Gross salary from the given basic salary {", gvn_basc_sal, "} =", gros_sal)

Output:

The Employee's Gross salary from the given basic salary { 23000 } = 29440.0

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the basic salary as user input using the float(input()) function and store it in a variable.
  • Calculate the value of da from the above given mathematical formula and store it in another variable.
  • Calculate the value of hr from the above given mathematical formula and store it in another variable.
  • Calculate the value of da-on-ta from the above given mathematical formula and store it in another variable.
  • Calculate the gross salary from the above given mathematical formula and store it in another variable.
  • Print the Gross salary of an employee from the given basic salary.
  • The Exit of the program.

Below is the implementation:

# Give the basic salary as user input using the float(input()) function and
# store it in a variable.
gvn_basc_sal = float(input("Enter some random Number = "))
# Calculate the value of da from the above given mathematical formula and store
# it in another variable.
gvn_da = (float)(15 * gvn_basc_sal) / 100.0
# Calculate the value of hr from the above given mathematical formula and store
# it in another variable.
gvn_hr = (float)(10 * gvn_basc_sal) / 100.0
# Calculate the value of da-on-ta from the above given mathematical formula and store
# it in another variable.
gvn_da_on_ta = (float)(3 * gvn_basc_sal) / 100.0
# Calculate the gross salary using the above given mathematical formula and store
# it in another variable.
gros_sal = gvn_basc_sal + gvn_da + gvn_hr + gvn_da_on_ta
# Print the Gross salary of an employee from the given basic salary.
print(
    "The Employee's Gross salary from the given basic salary {", gvn_basc_sal, "} =", gros_sal)

Output:

Enter some random Number = 50000
The Employee's Gross salary from the given basic salary { 50000.0 } = 64000.0

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.

Python Program to Enter Basic Salary and Calculate Gross Salary of an Employee Read More »

Program to Find Median of List

Python Program to Find Median of List

In the previous article, we have discussed Python Program to get the Last Word from a String

Median:

In general, the median is the middle value of a sorted list of elements. To find the median, we must first sort the data if it is not already sorted. The middle value can then be extracted and printed. If the number of elements in the list is even, we can calculate the median by taking the average of the list’s two middle values. Else take the middle value.

For example, let the given list is [ 1, 2, 4, 3, 6, 5].

The sorted form of the given list is [1, 2, 3, 4, 5, 6].

The median is the average of the middle two elements i.e.(3+4) /2. Therefore, the Median is  3.5.

Examples:

Example1:

Input: 

Given List = [ 5, 2, 4 ,2, 1]

Output:

The Median of List of Elements = 2

Example2:

Input:

Given List = [9, 6, 1, 4, 5, 2, 7, 8]

Output:

The Median of the Given List of Elements = 5.5

Program to Find Median of List :

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Below are the ways to perform to find the median of a List in python.

Method #1: Using Sort Function (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Sort the given List using the sort( ) function.
  • Calculate the length of the list using the len() function and store it in a variable.
  • Find the given list’s middle element by using (total length of list-1) divided by 2( zero indexing) and store it in a variable.
  • Check if the given list is even or odd using the If conditional statement.
  • If the given list’s length is even, the median is the average of the middle two elements.
  • If the length of the given list is odd, Median is the middle element.
  • Print the median of the above-given List.
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_list = [5, 2, 4, 2, 1]
# sorting the given list using sort() function
gvn_list.sort()
# Calculate the length of the list using the len() function and store it in a variable.
lst_leng = len(gvn_list)
# Find the middle element of the given List by using (total length of list-1)
# divided by 2( zero indexing)and store it in a variable.
mid_vlu = (lst_leng-1)//2
# Check if the given list is even or odd using the If conditional statement.
if(lst_leng % 2 == 0):
    # If the length of given list is even , median is the average of middle two elements.
    res_vlu = (gvn_list[mid_vlu] + gvn_list[mid_vlu+1])/2
else:
    # If the length of given list is odd , Median  is the middle element.
    res_vlu = gvn_list[mid_vlu]
print('The Median of the Given List of Elements =', res_vlu)

Output:

The Median of the Given List of Elements = 2

Method #2: Using Sort Function (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Sort the given List using the sort( ) function.
  • Calculate the length of the list using the len() function and store it in a variable.
  • Find the given list’s middle element by using (total length of list-1) divided by 2( zero indexing) and store it in a variable.
  • Check if the given list is even or odd using the If conditional statement.
  • If the given list’s length is even, the median is the average of the middle two elements.
  • If the length of the given list is odd, Median is the middle element.
  • Print the median of the above-given List.
  • The Exit of the program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_list = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# sorting the given list using sort() function
gvn_list.sort()
# Calculate the length of the list using the len() function and store it in a variable.
lst_leng = len(gvn_list)
# Find the middle element of the given List by using (total length of list-1)
# divided by 2( zero indexing)and store it in a variable.
mid_vlu = (lst_leng-1)//2
# Check if the given list is even or odd using the If conditional statement.
if(lst_leng % 2 == 0):
    # If the length of given list is even , median is the average of middle two elements.
    res_vlu = (gvn_list[mid_vlu] + gvn_list[mid_vlu+1])/2
else:
    # If the length of given list is odd , Median  is the middle element.
    res_vlu = gvn_list[mid_vlu]
print('The Median of the Given List of Elements =', res_vlu)

Output:

Enter some random List Elements separated by spaces = 9 6 4 1 5 2 7 8
The Median of the Given List of Elements = 5.5

The given list median value is printed.

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.

 

Python Program to Find Median of List Read More »