How to add to an empty list in python – Python: How to Create an Empty List and Append Items to it?

Python How to Create an Empty List and Append Items to it

How to add to an empty list in python:  An ordered list of values is a collection. There may be different types of values. A list is a container that is mutable. This means that the existing ones can be added, deleted, or modified.

The list of Pythons represents a finite sequence mathematical concept. List values are called list items or list elements. A list may multiple times contain the same value. Each event is considered to be a separate element.

In this article, we will look at how to create an empty list and adding elements to empty list in Python, Python append to empty list, Empty list append python, Append in empty list python, Add Value In Empty List Python, Create An Empty List And Append Python, Python Empty List, Append To Empty List Python, Python Create Empty List, Creating an nmpty list in python, Create Empty List Python, Add To Empty List Python, Add Element To Empty List Python, Python List Empty, Create Empty List And Append Python, Python Add To Empty List.

How to Create An Empty List and How to Append a list of Items in Python?

Initialize append empty list python: There are several ways to create and append values to list some of them are:

Creating a list:

Adding elements to list:

Creating a list

Method #1: Using [] symbol create an empty list in python

Make an empty list python: An empty list can be generated in Python by simply writing square brackets, i.e. []. If there are no arguments in the square brackets [, it returns an empty list.

Using [] symbol

Implementation:

# creating new list
newlist = []
# printing it
print("Newlist = ", newlist)

Output:

Newlist =  []

Method #2: Using list() Constructor create an empty list in python

How to empty list in python: The list class in Python has a constructor

list( [iterable] ).

It takes an optional statement, which is an iterable sequence, and constructs a list from these elements. It returns an empty list if Sequence is not given. Let’s use this to make a blank list.

Using list() Constructor

Implementation:

# creating new list
newlist = list()
# printing it
print("Newlist = ", newlist)

Output:

Newlist =  []

Adding items/elements to the list

Method #1: Using append() function add items to an empty list in python

Python initialize empty list: The built-in append() function can be used to add elements to the List. The append() method can only add one element to the list at a time; loops are used to add several elements to the list with the append() method. Since tuples are immutable, they can also be added to the list using the append method. Lists, unlike Sets, can be appended to an existing list using the append() form.

Using append() function

Below is the implementation:

# creating new empty list
newlist = list()
# adding items 1 2 3 to it
newlist.append(1)
newlist.append(2)
newlist.append(3)
# printing it
print("Newlist = ", newlist)

Output:

Newlist =  [1, 2, 3]

Method #2:Using insert() function add elements to an empty list in python

insert():

Make empty list python: It inserts the item in the list at the given index.

list.insert(index,element)

The append() method only adds elements to the end of the List; the insert() method is used to add elements to the desired location. Unlike append(), which only needs one statement, insert() requires two (index,element).

creating new empty list Using insert() function

Below is the implementation:

# Taking a list with values
newlist = ['this', 'is', 'BTechGeeks']
# inserting element hello to 2 nd index using insert()
newlist.insert(2, 'hello')
# printing the list
print("list = ", newlist)

Output:

list =  ['this', 'is', 'hello', 'BTechGeeks']

Method #3:Using extend() function add items to an empty list in python

Create an empty list python: There is one more method to add elements other than the append() and insert() methods, extend(), used at the end of the list to add multiple elements simultaneously.

Note: the methods append() and extend() can only add elements at the end.

Below is the implementation:

# Taking a list with values
newlist = ['this', 'is', 'BTechGeeks']
# extend this newlist with multiple items
newlist.extend(['hello', 'python', 234])
# printing the list
print("list = ", newlist)

Output:

list =  ['this', 'is', 'BTechGeeks', 'hello', 'python', 234]

Recommended Reading On: Python : How to Add an Element in List ?

Test yourself:

  1. How To Add Elements In Empty List In Python?
  2. How To Append To An Empty List In Python?
  3. How To Add Elements In Empty List In Python Using For Loop?
  4. How To Add Elements To An Empty List In Python?
  5. How To Append In Empty List In Python?
  6. How To Add Elements To Empty List In Python?

Related Programs:

Check if process is running – Python: Check if a Process is Running by Name and find its Process ID (PID) | How to find the PID of a Running Process?

Python Check if a Process is Running by Name and find its Process ID (PID)

Check if process is running: Do you want to determine whether a process is running or not by name and find its Process ID as well? Then, this is the right place as this article will shed light on you completely on how to check if a process is running or not using Name. We have provided enough examples for finding the Process ID PID by Name for better understanding. You can visit our site online to seek guidance or simply copy-paste the code from our portal and try to apply this knowledge and write a code on your own.

How to Check if there exists a Process running by Name and find its Process ID (PID)?

Python : get running processes: In this article, we will discuss finding a running process PIDs by name using psutil.

psutil library can be installed by using

pip install psutil

Determine if Process is Running or Not

Follow the simple guidelines for checking if a process is running or not. They are as such

  • def findProcessIdByName(processName):
  • for proc in psutil. process_iter():
  • pinfo = proc. as_dict(attrs=[‘pid’, ‘name’, ‘create_time’])
  • if processName. lower() in pinfo[‘name’]. lower() :
  • except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) :

To check if a process is running or not we will iterate over all the running processes using psutil.process_iter() and during iteration match the process name.

So let’s see this example to check chrome process is running or not.

import psutil
def checkProcessRunning(processName):
    # Checking if there is any running process that contains the given name processName.
    #Iterate over the all the running process
    for proc in psutil.process_iter():
        try:
            # Check if process name contains the given name string.
            if processName.lower() in proc.name().lower():
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False;

# Checking if any chrome process is running or not.
if checkProcessRunning('chrome'):
    print('Yes chrome process was running')
else:
    print('No chrome process was running')

How to Check if a Process is Running or Not

Output:

No chrome process was running

As in my system chrome instances are not running it will return False.

Finding the Process ID(PID) by Name?

In the above program, we checked any chrome instances were running or not. But in this example, we will see how to get the Process ID of a running ‘chrome.exe’ process. For that we will iterate over all the running processes and during iteration for each process whose name contains the given string, we will keep its information in a list. The following code helps you find the PID of a running process by Name.

import psutil
def findProcessIdByName(processName):
    # Here is the list of all the PIDs of a all the running process 
    # whose name contains the given string processName
    listOfProcessObjects = []
    #Iterating over the all the running process
    for proc in psutil.process_iter():
       try:
           pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time'])
           # Checking if process name contains the given name string.
           if processName.lower() in pinfo['name'].lower() :
               listOfProcessObjects.append(pinfo)
       except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) :
           pass
    return listOfProcessObjects;

# Finding PIDs od all the running instances of process 
# which contains 'chrome' in it's name
listOfProcessIds = findProcessIdByName('chrome')
if len(listOfProcessIds) > 0:
   print('Process Exists | PID and other details are')
   for elem in listOfProcessIds:
       processID = elem['pid']
       processName = elem['name']
       processCreationTime =  time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(elem['create_time']))
       print((processID ,processName,processCreationTime ))
else :
   print('No Running Process found with this text')

Finding Process ID by Name

Now, the contents of the list

(2604, 'chrome.exe', '2018-11-10 19:12:13')
(4276, 'chrome.exe', '2018-11-10 19:12:14')
(9136, 'chrome.exe', '2018-11-10 19:12:14')
(9616, 'chrome.exe', '2018-11-10 19:43:41')
(12904, 'chrome.exe', '2018-11-10 19:12:13')
(13476, 'chrome.exe', '2018-11-10 20:03:04')
(15520, 'chrome.exe', '2018-11-10 20:02:22')

This can also be done using a single line using list comprehension  i.e

# Finding the PIDs of all the running instances of process that contains 'chrome' in it's name
procObjList = [procObj for procObj in psutil.process_iter() if 'chrome' in procObj.name().lower() ]

And the same output will come like

psutil.Process(pid=2604, name='chrome.exe', started='19:12:13')
psutil.Process(pid=4276, name='chrome.exe', started='19:12:14')
psutil.Process(pid=9136, name='chrome.exe', started='19:12:14')
psutil.Process(pid=9616, name='chrome.exe', started='19:43:41')
psutil.Process(pid=12904, name='chrome.exe', started='19:12:13')
psutil.Process(pid=13476, name='chrome.exe', started='20:03:04')
psutil.Process(pid=15520, name='chrome.exe', started='20:02:22')

Related Programs:

 

Textfiles b – Python Program to Generate 26 Text Files named A.txt, B.txt, and so on up to Z.txt

Python Program to Generate 26 Text Files named A.txt, B.txt, and so on up to Z.txt

Files In Python:

Textfiles b: A file is a piece of data or information stored on a computer’s hard drive. You’re already familiar with a variety of file kinds, including music, video, and text files. Manipulation of these files is trivial with Python. Text files and binary files are the two types of files that are commonly used. Binary files contain binary data that can only be read by a computer, whereas text files include plain text.

For programmers and automation testers, Python file handling (also known as File I/O) is a crucial topic. Working with files is required in order to write to or read data from them.

In addition, if you didn’t know, I/O activities are the most expensive techniques via which software might fail. As a result, when implementing file processing for reporting or any other reason, you should proceed with caution. The construction of a high-performance application or a robust solution for automated software testing can benefit from optimizing a single file activity.

The task is to generate 26 Text Files with names A.txt, B.txt, and so on in Python. Open Txt Files In Python, Python Write Txt, Python Read Txt File.

Program to Generate 26 Text Files named A.txt, B.txt, and so on up to Z.txt in Python

Logic:

Here we iterate from 65(Ascii value of ‘A’) to 65+26 and convert this ASCII value to the character using chr() function.

We make the new files using the write function.

Write function creates the file if the file doesn’t exist.

Approach:

  • Here we iterate from 65(Ascii value of ‘A’) to 65+26(Z) using For loop. So Z.
  • Convert this ASCII value to the character using chr() function and store it as the filename.
  • Open this file in writing mode by passing the first argument as filename and the second argument mode as w(Writing mode).
  • Write some dummy data to file using the writelines() function.
  • Here we write the character value to file.
  • The Exit of the Program.

Below is the Implementation:

# Here we iterate from 65(Ascii value of 'A') to 65+26(Z) using For loop
for i in range(65, 65+26):
    # convert this ASCII value to the character using chr() function and store it as filename
    filename = chr(i)+'.txt'
    # Open this file in writing mode by passing the first argument as filename and second argument mode as w(Writing mode)
    with open(chr(i) + ".txt", "w") as file:
      # Write some dummy data to file using the writelines() function
      # Here we write the character value to file
        file.writelines(chr(i))

Output:

Explanation:

  • The file path is stored in the variable ‘file name.’ Change the value of this variable to the path of your own file.
  • Dragging and dropping a file onto the terminal will show its path. The code will not run unless you change the value of this variable.
  • The file will be opened in reading mode. Use the open() function to open a file. The path to the file is the method’s first parameter, and the mode to open the file is the method’s second parameter.
  • When we open the file, we use the character ‘w’ to signify write-mode.
  • Here we get all the filenames using the ASCII values(Converting them to characters).
  • Here write mode creates the file with the above filename.

Sample Implementation in google colab:

Answer these:

  1. Write A Python Program To Generate 26 Text Files Named A.Txt, B.Txt, And So On Up To Z.Txt?
  2. How To Create A Text File In Python?
  3. How To Create Text File In Python?
  4. Create A Text File In Python?

Python Program to Find the Sum of Series 9+99+999…..+N

Program to Find the Sum of Series 9+99+999.....+N

In the previous article, we have discussed Python Program to Remove the last Word from the String/Sentence

Given a number N and the task is to find the sum of the given series (9+99+999…..+N) for the given number in Python.

Examples:

Example1:

Input:

Given Number =6

Output:

The total sum of the series till the given number { 6 } =  1111104

Example2:

Input:

Given Number =11

Output:

The total sum of the series till the given number { 11 } =  111111111099

Program to Find the Sum of Series 9+99+999…..+N in Python

Below are the ways to find the sum of the given series (9+99+999…..+N) for the given number in Python

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number N as static input and store it in a variable.
  • Take a variable say resltsum which gives the sum of the given series till N and initialize its value to 0.
  • Take another variable say k and initialize its value with 9.
  • Iterate from 1 to the given number using the for loop.
  • Inside the loop, add the value of k to the above-initialized resltsum and store it in the same variable resltsum.
  • Calculate the value of (k*10)+9 and store it in the same variable k.
  • Print the resltsum value which is the result of the series till the given Number N.
  • The Exit of the Program.

Below is the implementation:

# Give the number N as static input and store it in a variable.
gvn_numb = 6
# Take a variable say resltsum which gives the sum of the given series till N and
# initialize its value to 0.
resltsum = 0
# Take another variable say k and initialize its value with 9.
k = 9
# Iterate from 1 to the given number using the for loop.
for itr in range(1, gvn_numb+1):
  # Inside the loop, add the value of k to the above-initialized resltsum and store
  # it in the same variable resltsum.
    resltsum += k
  # Calculate the value of (k*10)+9 and store it in the same variable k.
    k = (k*10)+9
# Print the resltsum value which is the result of the series till the given Number N.
print(
    "The total sum of the series till the given number {", gvn_numb, "} = ", resltsum)

Output:

The total sum of the series till the given number { 6 } =  1111104

Method #2: Using For loop (User Input)

Approach:

  • Give the number N as user input using the int(input()) function and store it in a variable.
  • Take a variable say resltsum which gives the sum of the given series till N and initialize its value to 0.
  • Take another variable say k and initialize its value with 9.
  • Iterate from 1 to the given number using the for loop.
  • Inside the loop, add the value of k to the above-initialized resltsum and store it in the same variable resltsum.
  • Calculate the value of (k*10)+9 and store it in the same variable k.
  • Print the resltsum value which is the result of the series till the given Number N.
  • The Exit of the Program.

Below is the implementation:

# Give the number N as user input using the int(input()) function and
# store it in a variable.
gvn_numb = int(input("Enter some random Number = "))
# Take a variable say resltsum which gives the sum of the given series till N and
# initialize its value to 0.
resltsum = 0
# Take another variable say k and initialize its value with 9.
k = 9
# Iterate from 1 to the given number using the for loop.
for itr in range(1, gvn_numb+1):
  # Inside the loop, add the value of k to the above-initialized resltsum and store
  # it in the same variable resltsum.
    resltsum += k
  # Calculate the value of (k*10)+9 and store it in the same variable k.
    k = (k*10)+9
# Print the resltsum value which is the result of the series till the given Number N.
print(
    "The total sum of the series till the given number {", gvn_numb, "} = ", resltsum)

Output:

Enter some random Number = 11
The total sum of the series till the given number { 11 } = 111111111099

The best way to learn Python for Beginners is to practice as much as they can taking help of the Sample Python Programs For Beginners. Using them you can develop code on your own and master coding skills.

Read more: Python Program to Find Sum of Series 1-2+3-4+5…+N

Explore these:

  1. 9+99+999…N Terms
  2. Sum Of Series In Python
  3. Sum Of Series Program In Python
  4. 9+99+999.

Related Posts On:

Equation of line passing through two points – Python Program to Find Line Passing Through 2 Points

Program to Find Line Passing Through 2 Points

Equation of line passing through two points: In the previous article, we have discussed Python Program to Find N’th Pentagonal Number
Given two points P, Q in the coordinate plane and the task is to find the equation of the line passing through both the given points.

This type of conversion is very useful in many geometric algorithms such as line intersection, finding the circumcenter of a triangle, finding the incenter of a triangle, etc.

Let P(x1, y1) and Q(x2, y2) be the given two points. We can now find the equation of the line formed by these points.

Any line can be written as

ax + by = c

Let the two points form a straight line. As a result,

ax1 + by1 = c
ax2 + by2 = c

Formulas:

Line passing through two points: We can change the following values to ensure that all of the equations hold true:

a = y2 – y1
b = x1 – x2

c = ax1 + by1

Examples:

Example1:

Input:

Given First Point = ( 4 , 2 ) 
Given Second Point = ( 3 , 8 )

Output:

The Equation of line passing through the given two points is:  6 x +  1 y =  26

Example2:

Input:

Given First Point = ( 6 , 3 ) 
Given Second Point = ( 1 , 4 )

Output:

The Equation of line passing through the given two points is: 1 x + 5 y = 21

Program to Find Line Passing Through 2 Points in Python

Find the equation of the line passing through two points: Below are the ways to find the equation of the line passing through both the given points in python:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the first point as static input and store it in two variables.
  • Give the second point as static input and store it in another two variables.
  • Subtract b1 from b2 and store it in another variable say p.
  • Subtract a2 from b1 and store it in another variable say q.
  • Calculate the value of p*(a1) + q*(b1) and store it in a variable say r.
  • Check if the value of q is less than 0 using the if conditional statement.
  • If it is true, then print the respective line equation using the variables p,q,r.
  • Else, print the respective line equation using the variables p,q,r.
  • The Exit of the Program.

Below is the implementation:

# Give the first point as static input and store it in two variables.
a1 = 4
b1 = 2
# Give the second point as static input and store it in another two variables.
a2 = 3
b2 = 8
# Subtract b1 from b2 and store it in another variable say p.
p = b2 - b1
# Subtract a2 from b1 and store it in another variable say q.
q = a1 - a2
# Calculate the value of p*(a1) + q*(b1) and store it in a variable say r.
r = p*(a1) + q*(b1)
# Check if the value of q is less than 0 using the if conditional statement.
if(q < 0):
  # If it is true, then print the respective line equation using the variables p,q,r.
    print("The Equation of line passing through the given two points is:",
          p, "x ", q, "y = ", r)
else:
  # Else, print the respective line equation using the variables p,q,r.
    print("The Equation of line passing through the given two points is: ",
          p, "x + ", q, "y = ", r)
#include <iostream>

using namespace std;

int main ( ) {
  int a1 = 4;
  int b1 = 2;
  int a2 = 3;
  int b2 = 8;
  double p = b2 - b1;
  double q = a1 - a2;
  double r = p * ( a1 ) + q * ( b1 );
  if ( ( q < 0 ) && ( r < 0 ) ) {
    cout << "The Equation of line passing through the given two points is:" << p << "x " << q << "y = " << r << endl;
  }
  else {
    cout << "The Equation of line passing through the given two points is: " << p << "x + " << q << "y = " << r << endl;
  }
  return 0;
}

Output:

The Equation of line passing through the given two points is:  6 x +  1 y =  26

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the first point as user input using map(),int(),split() functions and store it in two variables.
  • Give the second point as user input using map(),int(),split() functions and store it in two variables.
  • Subtract b1 from b2 and store it in another variable say p.
  • Subtract a2 from b1 and store it in another variable say q.
  • Calculate the value of p*(a1) + q*(b1) and store it in a variable say r.
  • Check if the value of q is less than 0 using the if conditional statement.
  • If it is true, then print the respective line equation using the variables p,q,r.
  • Else, print the respective line equation using the variables p,q,r.
  • The Exit of the Program.

Below is the implementation:

# Give the first point as user input using map(),int(),split() functions
# and store it in two variables.
a1, b1 = map(int, input(
    'Enter some random first point values separated by spaces = ').split())
# Give the second point as user input using map(),int(),split() functions
# and store it in two variables.
a2, b2 = map(int, input(
    'Enter some random second point values separated by spaces = ').split())
# Subtract b1 from b2 and store it in another variable say p.
p = b2 - b1
# Subtract a2 from b1 and store it in another variable say q.
q = a1 - a2
# Calculate the value of p*(a1) + q*(b1) and store it in a variable say r.
r = p*(a1) + q*(b1)
# Check if the value of q is less than 0 using the if conditional statement.
if(q < 0):
  # If it is true, then print the respective line equation using the variables p,q,r.
    print("The Equation of line passing through the given two points is:",
          p, "x ", q, "y = ", r)
else:
  # Else, print the respective line equation using the variables p,q,r.
    print("The Equation of line passing through the given two points is: ",
          p, "x + ", q, "y = ", r)

Output:

Enter some random first point values separated by spaces = 6 3
Enter some random second point values separated by spaces = 1 4
The Equation of line passing through the given two points is: 1 x + 5 y = 21

Enhance your coding skills with our list of Python Basic Programs provided and become a pro in the general-purpose programming language Python in no time.

Python Program to Move all Negative Elements to End in Order with Extra Space Allowed

Program to Move all Negative Elements to End in Order with Extra Space Allowed

In the previous article, we have discussed Python Program to Split the Array/List and add the First Part to the End
Given a list that contains the negative and positive elements the task is to move all the negative elements to the end of the list.

Examples:

Example1:

Input:

Given List =[1, 9, -3, 6, 8, 11, 35, -5, -7, 10, -1, -2, -3]

Output:

The given list after moving negative elements to the end is [1, 9, 6, 8, 11, 35, 10, -3, -5, -7, -1, -2, -3]

Example2:

Input:

Given List = [-7 11 56 -3 -8 12 17 -25 -8 -11 -6 9 10]

Output:

The given list after moving negative elements to the end is [11, 56, 12, 17, 9, 10, -7, -3, -8, -25, -8, -11, -6]

Program to Move all Negative Elements to End in Order with Extra Space Allowed in Python

There are several ways to move all the negative elements to the end of the list some of them are:

Method #1: Using List Comprehension (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Using list comprehension and if conditional statements separate the positive numbers from the list and store it in a variable to say the positive list.
  • Using list comprehension and if conditional statements separate the negative numbers from the list and store it in a variable to say the negative list.
  • Add the positive list and negative list using the + operator and store it in another variable to say result list(This operation moves all the negative list).
  • Print the result list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvnlst = [1, 9, -3, 6, 8, 11, 35, -5, -7, 10, -1, -2, -3]
# Using list comprehension and if conditional statements
# separate the positive numbers from the list
# and store it in a variable to say the positive list.
pstivelist = [elemn for elemn in gvnlst if elemn >= 0]
# Using list comprehension and if conditional statements
# separate the negative numbers from the list and store it
# in a variable to say the negative list.
ngtivelist = [elemn for elemn in gvnlst if elemn < 0]
# Add the positive list and negative list using the + operator
# and store it in another variable to say result list
# (This operation moves all the negative list).
resltlist = pstivelist+ngtivelist
# Print the result list.
print('The given list after moving negative elements to the end is', resltlist)

Output:

The given list after moving negative elements to the end is [1, 9, 6, 8, 11, 35, 10, -3, -5, -7, -1, -2, -3]

Method #2: Using List Comprehension (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Using list comprehension and if conditional statements separate the positive numbers from the list and store it in a variable to say the positive list.
  • Using list comprehension and if conditional statements separate the negative numbers from the list and store it in a variable to say the negative list.
  • Add the positive list and negative list using the + operator and store it in another variable to say result list(This operation moves all the negative list).
  • Print the result 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.
gvnlstt = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Using list comprehension and if conditional statements
# separate the positive numbers from the list
# and store it in a variable to say the positive list.
pstivelist = [elemn for elemn in gvnlstt if elemn >= 0]
# Using list comprehension and if conditional statements
# separate the negative numbers from the list and store it
# in a variable to say the negative list.
ngtivelist = [elemn for elemn in gvnlstt if elemn < 0]
# Add the positive list and negative list using the + operator
# and store it in another variable to say result list
# (This operation moves all the negative list).
resltlist = pstivelist+ngtivelist
# Print the result list.
print('The given list after moving negative elements to the end is', resltlist)

Output:

Enter some random List Elements separated by spaces = -7 11 56 -3 -8 12 17 -25 -8 -11 -6 9 10
The given list after moving negative elements to the end is [11, 56, 12, 17, 9, 10, -7, -3, -8, -25, -8, -11, -6]

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 Accept a Hyphen Separated Sequence of Words as Input and Print the Words in a Hyphen-Separated Sequence after Sorting them Alphabetically

Program to Accept a Hyphen Separated Sequence of Words as Input and Print the Words in a Hyphen-Separated Sequence after Sorting them Alphabetically

Strings in Python:

“String is a character collection or array”

Well in Python too, for the string data type, we say the same definition. The string is a sequenced character array and is written within single, double, or three quotes. Also, Python does not have the data type character, thus it is used as a string of length 1 if we write ‘s’.

Given a hyphen-separated sequence of strings, the task is to sort the strings and print them as hyphen-separated strings in Python.

Examples:

Example1:

Input:

given hyphen-separated string =hello-this-is-btechgeeks

Output:

The string before modification =  hello-this-is-btechgeeks
The string after modification =  btechgeeks-hello-is-this

Example2:

Input:

given hyphen-separated string =good-morning-codechef

Output:

The string before modification = good-morning-codechef
The string after modification = codechef-good-morning

Examples3:

Input:

given hyphen-separated string =btechgeeks-online-platform-fror-coding-students

Output:

The string before modification = btechgeeks-online-platform-fror-coding-students
The string after modification = btechgeeks-coding-fror-online-platform-students

Program to Accept a Hyphen Separated Sequence of Words as Input and Print the Words in a Hyphen-Separated Sequence after Sorting them Alphabetically in Python

Below are the ways to accept a hyphen-separated sequence of strings, the task is to sort the strings and print them as hyphen-separated strings in Python.

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Method #1:Using split() and join() functions(Static Input)

Approach:

  • Give the hyphen-separated string as static input and store it in a variable.
  • Split the hyphen-separated strings into a list of strings using the split() function and store it in a variable.
  • sort the given list using the sort() function.
  • Print the sorted sequence by joining the words in the list with a hyphen.
  • The Exit of the program.

Below is the implementation of the above approach:

# Give the string as static input and store it in a variable.
givn_strng = 'hello-this-is-btechgeeks'
# print the string before modification
print('The string before modification = ', givn_strng)
# Split the hyphen-separated strings into a list of strings using the split()
# function and store it in a variable.
wordsLis = givn_strng.split('-')
# sort the given list using the sort() function.
wordsLis.sort()
# Print the sorted sequence by joining the words in the list with a hyphen.
resultwords = '-'.join(wordsLis)
# print the resultwords
print('The string after modification = ', resultwords)

Output:

The string before modification =  hello-this-is-btechgeeks
The string after modification =  btechgeeks-hello-is-this

Explanation:

  • Give the hyphen-separated string as static input and store it in a variable.
  • The hyphen is used as a key to split the sequence, and the words are saved in a list.
  • Using the sort() function, the words in the list are sorted alphabetically.
  • The terms in the list are then connected together by utilizing a hyphen as a reference.
  • The word sequence is then printed in its sorted order.

Method #2:Using split() and join() functions(User Input)

Approach:

  • Give the hyphen-separated string as user input using the input() function.
  • Split the hyphen-separated strings into a list of strings using the split() function and store it in a variable.
  • sort the given list using the sort() function.
  • Print the sorted sequence by joining the words in the list with a hyphen.
  • The Exit of the program.

Below is the implementation of the above approach:

# Give the hyphen-separated string as user input using the input() function.
givn_strng = input('Enter some random string = ')
# print the string before modification
print('The string before modification = ', givn_strng)
# Split the hyphen-separated strings into a list of strings using the split()
# function and store it in a variable.
wordsLis = givn_strng.split('-')
# sort the given list using the sort() function.
wordsLis.sort()
# Print the sorted sequence by joining the words in the list with a hyphen.
resultwords = '-'.join(wordsLis)
# print the resultwords
print('The string after modification = ', resultwords)

Output:

Enter some random string = good-morning-codechef
The string before modification = good-morning-codechef
The string after modification = codechef-good-morning

Explanation:

  • As input, the user must enter a hyphen-separated string of words.
  • The hyphen is used as a key to split the sequence, and the words are saved in a list.
  • Using the sort() function, the words in the list are sorted alphabetically.
  • The terms in the list are then connected together by utilizing a hyphen as a reference.
  • The word sequence is then printed in its sorted order.
  • It is the fastest and efficient approach.

Related Programs:

Get diagonal of matrix python – Python Program to Find the Sum of all Diagonal Elements of a Matrix

Program to Find the Sum of all Diagonal Elements of a Matrix

Get diagonal of matrix python: In the previous article, we have discussed Python Program to Check Whether a Matrix is Diagonal or Not

Given a matrix and the task is to find the sum of all diagonal elements of a given matrix in python.

What is a matrix:

Python diagonal matrix: A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Diagonal Matrix:

The entries outside the main diagonal of a diagonal matrix are all 0; the word usually refers to square matrices.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Examples:

Example1:

Input:

Given Matrix : 
3 0 0
0 1 0
0 0 2

Output:

The Sum of all Diagonal elements of a given Matix =  6

Example2:

Input:

Given Matrix : 
1 2 3 
6 5 4 
7 8 9

Output:

The Sum of all Diagonal elements of a given Matix = 15

Program to Find the Sum of all Diagonal Elements of a Matrix in Python

Python get diagonal of matrix: Below are the ways to find the sum of all diagonal elements of a given matrix in python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Take a variable say diagnl_sum and initialize its value to zero.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is equal to m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then add the gvnmatrix[n][m] to the above-initialized diagnl_sum and store it in the same variable diagnl_sum.
  • Print the value of diagnl_sum to get the sum of all diagonal elements of a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[3, 0, 0], [0, 1, 0], [0, 0, 2]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
# Take a variable say diagnl_sum and initialize its value to zero.
diagnl_sum = 0
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is equal to m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n == m:
          # If the statement is true, then add the gvnmatrix[n][m] to the above-initialized
          # diagnl_sum and store it in the same variable diagnl_sum.
            diagnl_sum += mtrx[n][m]
# Print the value of diagnl_sum to get the sum of all diagonal elements of a given matrix.
print("The Sum of all Diagonal elements of a given Matix = ", diagnl_sum)

Output:

The Sum of all Diagonal elements of a given Matix =  6

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Take a variable say diagnl_sum and initialize its value to zero.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is equal to m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then add the gvnmatrix[n][m] to the above-initialized diagnl_sum and store it in the same variable diagnl_sum.
  • Print the value of diagnl_sum to get the sum of all diagonal elements of a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
    
# Take a variable say diagnl_sum and initialize its value to zero.
diagnl_sum = 0
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is equal to m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n == m:
          # If the statement is true, then add the gvnmatrix[n][m] to the above-initialized
          # diagnl_sum and store it in the same variable diagnl_sum.
            diagnl_sum += mtrx[n][m]
# Print the value of diagnl_sum to get the sum of all diagonal elements of a given matrix.
print("The Sum of all Diagonal elements of a given Matix = ", diagnl_sum)

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 1 2 3
Enter {3} elements of row {2} separated by spaces = 6 5 4
Enter {3} elements of row {3} separated by spaces = 7 8 9
The Sum of all Diagonal elements of a given Matix = 15

If you are learning Python then the Python Programming Example is for you and gives you a thorough description of concepts for beginners, experienced programmers.

Read more: Python Program to Find the Sum of an Upper Triangular Matrix

Answer these:

  1. How to find sum of diagonal elements of matrix in python
  2. How to get sum of diagonal elements in python
  3. How to add diagonal elements in matric in python
  4. How to find the sum of diagonal elements of a matrix in python

Related Posts On:

Python3 delete file – Python: How to remove files by matching pattern | wildcards | certain extensions only?

Python- How to remove files by matching pattern, wildcards, certain extensions only

Python find files matching pattern: In this ultimate tutorial, we are going to discuss how to remove files from a directory based on a matching pattern or wildcard, or specific extensions. You will get the information regarding these also, Python Os.Remove Wildcard, Python Delete File Wildcard, Python Remove Files With Wildcard, Python Delete Files With Wildcard, Python Remove Files Wildcard, Python Remove Files Matching Pattern, Delete File Python, Remove File Python, Python Os Delete File, Delete A File Python, Python Remove File Wildcard, Python Delete Files Matching Pattern, Python Remove Directory.

How to delete text files using different techniques?

Python remove all files in directory: Let’s discuss how to delete text files using different techniques, Suppose we have a directory that contains some log files and some text files and we want to delete all .txt files from that directory.

Then, continue your read so that you can successfully learn to remove files by matching patterns or wildcards by the following methods and techniques.

Remove files by pattern using glob.glob() & os.remove()

Python3 delete file: First, we will get a list of all file paths that match the specified patterns using glob.glob() and then delete all text files.

import os
import glob
# Get a list of all the file paths that ends with .txt from in specified directory
fileList = glob.glob('C://Users/HP/Desktop/A plus topper/*.txt')
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)

So you can see that it will remove all ‘.txt’ files in the directory ‘C:\\Users\HP\Desktop\A plus topper\*.txt’. It will remove all text files because we mention” *.txt “.

Get the list of files using glob.glob()

Python os remove file: glob.glob() accepts path name and finds the path of all the files that match the specified pattern. By default recursive parameter is False, which means that it will find files in the main directory, not in a subdirectory.

glob.glob(pathname, *, recursive=False)

As we have seen by this approach we can not recursively delete files from subdirectories. For that, we will find another solution,

Read More:

Recursively Remove files by matching pattern or wildcard

Python delete all files in directory: It will search all the ‘txt’ files including files in subdirectories because we will use 'C://Users/HP/Desktop/A plus topper/**/*.txt'‘ **  ‘ in it.

Then we can iterate over the list and delete each file one by one using os.remove().

import os
import glob
# get a recursive list of file paths that matches pattern including sub directories
fileList = glob.glob('C://Users/HP/Desktop/A plus topper/**/*.txt', recursive=True)
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except OSError:
        print("Error while deleting file")

It will delete all the text files from the directory and its sub-directories.

Recursively Remove files by matching pattern or wildcard using os.walk()

Python rm file: In this, we are going to use os.walk(). It generates filename in the given directory by walking over the tree structure in a top-down or bottom-up approach.

os.walk(top, topdown=True, onerror=None, followlinks=False)

It will return a tuple consisting of the main directory, a list of all subdirectories, and a list of all file names in the main directory.

Let’s use this os.walk() to get a list of all files in a given directory that matches a pattern. Then delete those files,

import os
import fnmatch
# Get a list of all files in directory
for rootDir, subdirs, filenames in os.walk('C://HP/Users/Desktop/A plus topper'):
    # Find the files that matches the given patterm
    for filename in fnmatch.filter(filenames, '*.txt'):
        try:
            os.remove(os.path.join(rootDir, filename))
        except OSError:
            print("Error while deleting file")

It will delete all the text files from the directory and also from its subdirectories.

Now we are going to create a Generic function to delete all the files from a given directory based on a matching pattern and it will also return the names of the files that were not deleted due to some error.

import os
import fnmatch
'''
Generic function to delete all the files from a given directory based on matching pattern
'''
def removeFilesByMatchingPattern(dirPath, pattern):
    listOfFilesWithError = []
    for parentDir, dirnames, filenames in os.walk(dirPath):
        for filename in fnmatch.filter(filenames, pattern):
            try:
                os.remove(os.path.join(parentDir, filename))
            except:
                print("Error while deleting file : ", os.path.join(parentDir, filename))
                listOfFilesWithError.append(os.path.join(parentDir, filename))
    return listOfFilesWithError
listOfErrors = removeFilesByMatchingPattern('/home/varung/Documents/python/logs/', '*.txt')
print('Files that can not be deleted : ')
for filePath in listOfErrors:
    print(filePath)

So in the above code, you can see that it will also return file names that can not be deleted.

Read also: How to delete a directory recursively using shutil.rmtree()

Analyze these: 

  • How To Delete File In Python
  • Python Remove File Wildcard
  • Delete Files Python
  • Python Rm File

Conclusion:

In this article, we have seen how to remove files from a directory based on matching patterns or wildcards, or certain extensions.

Python recursion list – Python Program to Find Maximum and Minimum Elements in List/Array Using Recursion

Program to Find Maximum and Minimum Elements in ListArray Using Recursion

Python recursion list: In the previous article, we have discussed Python Program For Division Two Numbers Operator Without Using Division(/) Operator

Given a list and the task is to find the maximum and minimum elements in a given List using recursion in python, Recursive Function To Find Maximum Element In List Python, Recursive Max Function Python, Python Recursion List, Python Max Of List, Min Element In List Python.

Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Examples:

Example1:

Input:

Given List = [1, 6, 3, 7, 8, 4]

Output:

The Maximum element in a given list [1, 6, 3, 7, 8, 4] = 8
The Minimum element in a given list [1, 6, 3, 7, 8, 4] = 1

Example2:

Input:

Given List = [20, 30, 40, 10, 50]

Output:

The Maximum element in a given list [20, 30, 40, 10, 50] = 50
The Minimum element in a given list [20, 30, 40, 10, 50] = 10

Program to Find Maximum and Minimum Elements in List/Array Using Recursion in Python

Below are the ways to find the maximum and minimum elements in a given List using recursion in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Calculate the length of the given list and store it in another variable.
  • Pass the given list and length of the given list as the arguments to the max_elemnt, min_elemnt functions.
  • Create a recursive function to say max_elemnt which takes the given list and length of the given list as the arguments and returns the maximum element in a given list using recursion.
  • Check if the length of the given list is 1 using the if conditional statement.
  • If the statement is true, then return the first element of the list.
  • Return maximum of (gven_lst[len_lst – 1], max_elemnt(gven_lst, len_lst – 1) {Recursive logic}.
  • Create a recursive function to say min_elemnt which takes the given list and length of the given list as the arguments and returns the minimum element in a given list using recursion.
  • Check if the length of the given list is 1 using the if conditional statement.
  • If the statement is true, then return the first element of the list.
  • Return minimum of (gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1) {Recursive logic}.
  • Print the maximum element of the given list.
  • Print the minimum element of the given list.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say max_elemnt which takes the given list and
# length of the given list as the arguments and returns the maximum element in a
# given list using recursion.


def max_elemnt(gven_lst, len_lst):
  # Check if the length of the given list is 1 using the if conditional statement.
    if len_lst == 1:
      # If the statement is true, then return the first element of the list.
        return gven_lst[0]
     # Return maximum of (gven_lst[len_lst - 1], max_elemnt(gven_lst, len_lst - 1)
     # {Recursive logic}.
    return max(gven_lst[len_lst - 1], max_elemnt(gven_lst, len_lst - 1))

# Create a recursive function to say min_elemnt which takes the given list and
# length of the given list as the arguments and returns the minimum element in a
# given list using recursion.


def min_elemnt(gven_lst, len_lst):
  # Check if the length of the given list is 1 using the if conditional statement.
    if len_lst == 1:
      # If the statement is true, then return the first element of the list.
        return gven_lst[0]
    # Return minimum of (gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1)
    # {Recursive logic}.
    return min(gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1))


# Give the list as static input and store it in a variable.
gven_lst = [1, 6, 3, 7, 8, 4]
# Calculate the length of the given list and store it in another variable.
len_lst = len(gven_lst)
# Pass the given list and length of the given list as the arguments to the max_elemnt,
# min_elemnt functions.
# Print the maximum element of the given list.
print("The Maximum element in a given list",
      gven_lst, "=", max_elemnt(gven_lst, len_lst))
# Print the minimum element of the given list.
print("The Minimum element in a given list",
      gven_lst, "=", min_elemnt(gven_lst, len_lst))

Output:

The Maximum element in a given list [1, 6, 3, 7, 8, 4] = 8
The Minimum element in a given list [1, 6, 3, 7, 8, 4] = 1

Method #2: Using Recursion (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the length of the given list and store it in another variable.
  • Pass the given list and length of the given list as the arguments to the max_elemnt, min_elemnt functions.
  • Create a recursive function to say max_elemnt which takes the given list and length of the given list as the arguments and returns the maximum element in a given list using recursion.
  • Check if the length of the given list is 1 using the if conditional statement.
  • If the statement is true, then return the first element of the list.
  • Return maximum of (gven_lst[len_lst – 1], max_elemnt(gven_lst, len_lst – 1) {Recursive logic}.
  • Create a recursive function to say min_elemnt which takes the given list and length of the given list as the arguments and returns the minimum element in a given list using recursion.
  • Check if the length of the given list is 1 using the if conditional statement.
  • If the statement is true, then return the first element of the list.
  • Return minimum of (gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1) {Recursive logic}.
  • Print the maximum element of the given list.
  • Print the minimum element of the given list.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say max_elemnt which takes the given list and
# length of the given list as the arguments and returns the maximum element in a
# given list using recursion.


def max_elemnt(gven_lst, len_lst):
  # Check if the length of the given list is 1 using the if conditional statement.
    if len_lst == 1:
      # If the statement is true, then return the first element of the list.
        return gven_lst[0]
     # Return maximum of (gven_lst[len_lst - 1], max_elemnt(gven_lst, len_lst - 1)
     # {Recursive logic}.
    return max(gven_lst[len_lst - 1], max_elemnt(gven_lst, len_lst - 1))

# Create a recursive function to say min_elemnt which takes the given list and
# length of the given list as the arguments and returns the minimum element in a
# given list using recursion.


def min_elemnt(gven_lst, len_lst):
  # Check if the length of the given list is 1 using the if conditional statement.
    if len_lst == 1:
      # If the statement is true, then return the first element of the list.
        return gven_lst[0]
    # Return minimum of (gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1)
    # {Recursive logic}.
    return min(gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1))



# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gven_lst = list(map(int, input( 'Enter some random List Elements separated by spaces = ').split()))
# Calculate the length of the given list and store it in another variable.
len_lst = len(gven_lst)
# Pass the given list and length of the given list as the arguments to the max_elemnt,
# min_elemnt functions.
# Print the maximum element of the given list.
print("The Maximum element in a given list",
      gven_lst, "=", max_elemnt(gven_lst, len_lst))
# Print the minimum element of the given list.
print("The Minimum element in a given list",
      gven_lst, "=", min_elemnt(gven_lst, len_lst))

Output:

Enter some random List Elements separated by spaces = 20 30 40 50 10
The Maximum element in a given list [20, 30, 40, 50, 10] = 50
The Minimum element in a given list [20, 30, 40, 50, 10] = 10

Applications On:

  1. Write A C Program To Find Maximum And Minimum Elements In Array Using Recursion
  2. Find Max Value In List Using Recursion Python
  3. Find Max Value In Array Using Recursion Python
  4. Find Max Value In List Python Recursion
  5. Find Max And Min In Array Using Recursion Python
  6. Find Max In List Python Recursion
  7. Find The Maximum Of A List Of Numbers Using Python
  8. Find Maximum And Minimum Element In An Array In Python
  9. Find Minimum Value In Array Recursion Java
  10. Recursively Find Max Value In Array
  11. Find Max In Array Python
  12. Find Max And Min In Array Using Recursion
  13. Find Max In Array Recursive
  14. Find Max Value In Array Using Recursion Java
  15. Find Max And Min In Array Using Recursion Java
  16. Recursive Function To Find Maximum Element In An Array C
  17. Program To Find Maximum And Minimum In Python
  18. Recursive Function To Find Smallest Element In An Array
  19. Recursive Algorithm To Find Maximum Element In An Array
  20. Check Number In Array Using Recursion In Python

Dive into numerous Python Programming Language Examples for practice and get the best out of the tutorial and learn python one step at a time.