Blogs  

How to Reverse a List in Python Learn Python List Reverse() Method

Introduction:

  1. As we know that the Python the Reversing a list is a way which takes up a more memory compared to an in-place reversal because it creates a (shallow) copy of the list. 

  2. In general, the reversing a List In-Place With the list. reverse() Method. 

  3. Every list in Python has a built-in reverse() method which is allowed to call to reverse the contents of the list object in-place.

  4. Reversing the list in-place means won't create a new list and copy the existing elements to it in reverse order.

Her I am going to discuss some of the important approach using which the reversal of the list in Python can be get done.

  1. Reversing a list with list.reverse() method 

  2. Using the Slicing Trick to Reverse a Python List, and 

  3. Creating Reverse Iterator with the reversed() Built-In Function

Reversing a list with list.reverse() method:

As we have already discussed earlier in the above segment that Every list in Python has a built-in reverse() method, so if it is needed then we can call this method to reverse the contents of the list object in-place. Reversing a list in-place means it won’t create and copy the existing elements to a new list. Instead, it directly modifies the original list object.

Let us consider the following example as below. Here I am trying to explain the technique in simpler way using the Python console based example.

Example:

>>> mylist = [1, 2, 3, 4, 5]
>>> mylist[1, 2, 3, 4, 5]
>>> mylist.reverse()
None
>>> mylist
[5, 4, 3, 2, 1]

Note:

  1. From the above example it is clear that when we are calling reverse() method then it returned ‘None’ but, modified the original list object. 

  2. When we are using the reverse() method then it is basically used to modifies the sequence of the element present in the list. 

  3. But it should be get noted that it does not return a reversed list values as a output but when we are going to print or display the list then it get printed out.

Using the Slicing Trick to Reverse a Python List:

Slicing in Python is another feature using which we can reverse the element of the list. If we need to apply this technique, then we have to use the following technique to make it possible. 

Let us consider the following example such as

 reverse_list(list):
    reversed_list = list[::-1]
    >>> mylist=[1, 2, 3, 4, 5]
    >>> mylist[::-1]
   [5, 4, 3, 2, 1]

Note:

  1. Here when we are going to use this technique then the structure of the list is get replicated but the elements are not. Hence, the elements are not duplicated thus saving space. 

  2. As you know that the list in Python are mutable so when we are going to apply this technique to the elements contained in a list then the object is get modified. Since the objects are get modified so that will be get reflected in other copies as well.

  3. The Slicing technique is fast and reliable for the developer. But sometimes it becomes difficult to understand when the decreasing readability of code is supposed to be get done. 

Creating Reverse Iterator with the reversed() Built-In Function:

It is another important technique in Python using which we can reverse the list element. When we are going to use the reversed() function then it will return an iterator using which if we need then we can be able to access elements in reverse order. 

But it should be get noted that If we are going to access a single individual element of the list in reverse order you can use this function. It does not reverse a list in-place neither it creates a copy.

Let us consider the following example as below.

>>> mylist = [1, 2, 3, 4, 5]
>>> for item in reversed(mylist):
...     print(item)
5
4
3
2
1
>>> mylist
>>> [1, 2, 3, 4, 5]

Note:

  1. In the above example it is clear that when we are going to use this function then it returns element of the list in reverse order using iterator pattern.

  2. Another way of getting a reverse list using list constructor.

To explain the concept of list constructor let us consider the following example as below.

>>> mylist = [1, 2, 3, 4, 5]
>>> list(reversed(mylist))
[5, 4, 3, 2, 1]
  1. Here in the above program I’m calling the list() constructor on the result of the reversed() function?.

  2. When we are using the list constructor it is used to built-in keeps iterating until the (reverse) iterator is exhausted.

  3. It is basically used to keep and puts all the elements which is get fetched from the iterator during the execution and puts into a new list object.

  4. And as a result a reversed shallow copy of the original list is get reformed and displayed.

  5. It is another convenient approach to reverse the list element in Python.

Scope @ NareshIT:

  1. At Naresh IT you will get a good Experienced faculty who will guide you, mentor you and nurture you to achieve your dream goal.

  2. Here you will get a good hand on practice in terms of practical industry-oriented environment which will definitely help you a lot to shape your future.

  3. During the designing process of application, we will let you know about the other aspect of the application too. 

  4. Our Expert trainer will let you know about every in’s and out’s about the problem scenario.

Achieving your dream goal is our motto. Our excellent team is working restlessly for our students to click their target. So, believe on us and our advice, and we assured you about your sure success. 

 

How to Parse and Modify XML in Python

Introduction:

  1. As we know that the Python is more powerful language which offer great tools for data crunching and preparation, as well as for complex scientific data analysis and modelling. 

  2. In most of the cases we often require parsing the data which is being written in different languages like C, C++ and Java.

  3. Here the Python is used to provides us a numerous enriched functionable libraries which may be get used to parse the data which is being written in other languages. 

  4. Here I am going to discuss the Python XML Parser, which will let you know to learn how to parse XML using Python.

  5. Python has multiple implementations including Jython, scripted in Java language for Java Virtual Machine.

  6. Most of the Python modules work on community development model and are open-source and free.

Here as stated earlier above, I am going to discuss the Python XML Parser, which will let you know to learn how to parse XML using Python.

What is XML?

  1. The XML is basically used to defined and referred as Extensible Markup Language. 

  2. It is having almost similar syntax like HTML in its appearance when we are going to make the code.

  3. It was first get designed for the purpose of storing and transportation of data. 

  4. It has a simple structural approach so that it can be both human- and machine-readable form.

  5. Technically the XML is specially get used for the presentation of data in the schema.

  6. Whereas if we consider the HTML then it is basically used for defining about what data is being used. 

  7. In general way of appearance, the XML is exclusively designed to send and receive data back when we are going to consider the clients and servers interactive modules or application, whereas the HTML is basically used for Webpage designing concept.

Let us consider the following example which will let you know how to write a XML file in Python. Mostly in Python 3 when we need to write an XML file it has to go through the following manner.

  1. As we know that the XML do not have predefined tags like HTML. 

  2. So, we need to create the Tag. Here in XML while writing the XML file or program the author has to define his/her own tags, and in addition with this he/she need to define the document structure too. 

  1. Here in Python3 we will be using “minidom” library for accomplishing the above task. 

  2. This module does not come built-in with Python. 

  3. So, when we need to go for the same, we need to install this using the below command in the terminal.

pip install minidom

Python XML Parsing Modules:

In Python the XML Parsing modules we are going to parse the XML document. Python basically have two modules to accomplish this task such as 

  1.  xml.etree.ElementTree module and 

  2. Minidom (Minimal DOM Implementation). 

As I have already discussed above that the Parsing is a process which is basically used to read information from a specific file being specified and splitting it into pieces by identifying parts of that particular XML file.

Let’s now see how we can use these modules to parse XML data.

Xml.etree.ElementTree Module:

  1. This module is basically get used for providing us the format for XML data in a tree structure.

  2. It is the structure which is the most natural representation of hierarchical data.

  3. Here while the representing the element the type is basically used to allow the storage of hierarchical data structures in memory.

  4. It basically uses the property for representing the data value. The details has been mentioned as below.

Tag Property:   This is a property which is named as Tag which is a string representing the type of data being stored. 

Attributes Property: It is basically used to consist of a number of sub attributes that are get stored as dictionaries. It is more concrete and precise.

Text String Property: It is basically a text string type which is having the information that we are going to require to be displayed when we need.

Tail String Property: It is another property like above but can have the tail strings. It is Optional and being used if necessary.

Child Elements Property: It is basically get used when we are going for number of child elements that need to be get stored as sequences.

The Xml.etree.ElementTree Module is basically used to have the following modules which is mainly used for parsing the XML file. Such as parse() function, and  fromstring() function.

parse() function:

 This function is basically get used when we need to parse the XML document when it is get supplied in the form of File.

Let us consider the following example as mentioned below.

import xml.etree.ElementTree as ET

mytree = ET.parse('sample.xml')

myroot = mytree.getroot()

print(myroot)

fromstring() function:

Like similar to above this method is basically used when we need to parse the XML document when it is get supplied as a string. i.e within triple quotes.

Let us consider the following example which will let you know and helps you to understand the concept.

import xml.etree.ElementTree as ET
data='''<?xml version="1.0" encoding="UTF-8"?>
<metadata>
<food>
    <item name="breakfast">Idly</item>
    <price>$2.5</price>
    <description>
   Two idly's with chutney
   </description>
    <calories>553</calories>
</food>
</metadata>
'''
myroot = ET.fromstring(data)
#print(myroot)
print(myroot.tag)

Finding Elements of Interest:

It is another important concept which deals with the root. The root is basically getting consists of child tags as well. Here it should be get noted that if we need to retrieve the child of the root tag, then we need to proceed as follows.

Example:

for x in myroot[0]:
     print(x.tag, x.attrib)

Here in the above code when it is get subjected to run then it will retrieve the child attributes and tags values.

Modifying XML files:

As you know that if you need then the elements which are present in your XML file that can be manipulated. Here we need to use the set() function to manipulate the content of the file. 

For example, if we need to add something to our existing XML file then we can able to proceed as follows.

Adding to XML:

The following example shows how you can add something to the description of items.

for description in myroot.iter('description'):
     new_desc = str(description.text)+'wil be served'
     description.text = str(new_desc)
     description.set('updated', 'yes')
 mytree.write('new.xml')

So, if we need to add the content then we can be able to write the above code to our existing program.

Deleting from XML:

Like similar to above if we need to delete the attributes or sub-elements using ElementTree approach then here we can use the pop() method. Like the set() which is used for adding and modifying the content, This method will remove the desired attribute or element that is not needed by the user form the XML documents.

Let us consider the same example mentioned earlier, but now to remove the attribute we have to write the following code as mentioned below.

myroot[0][0].attrib.pop('name', None)
 # create a new XML file with the results
mytree.write('output5.xml')

xml.dom.minidom Module:

  1. Like similar to Xml.etree.ElementTree Module,  This module is basically used by people who are familiar and proficient with DOM (Document Object module). 

  2. It should be get noted that the DOM applications often start by parsing XML into DOM. 

  3. In xml.dom.minidom, if we need to proceed then  we need to follows as:

parse() function:

As mentioned earlier in the above it is the first method which is basically used when we know we are supplying the XML file to be parsed as a parameter.  

For example:

from xml.dom import minidom
p1 = minidom.parse("sample.xml");

parseString() Method:

This method is used when you want to supply the XML to be parsed as a string.

Let us consider the following example as mentioned below where we are supplying the XML to be parsed as a string.

minidom.parseString('<myxml>Using<empty/> parseString</myxml>')

Finding Elements of Interest:

When the file is already been parsed, if we need to display the content of the file, the output that is returned displays a message that the variable storing the parsed data is an object of DOM.

Let us consider the following syntax as mentioned below.

print(minidom.parse('sample.xml'))

Accessing Elements

If we need to access the element, then we may use the methods such as GetElementByTagName.

Let us consider the following syntax as mentioned below.

print(dat.getElementsByTagName('item')[0])

Scope @ NareshIT:

  1. At Naresh IT you will get a good Experienced faculty who will guide you, mentor you and nurture you to achieve your dream goal.

  2. Here you will get a good hand on practice in terms of practical industry-oriented environment which will definitely help you a lot to shape your future.

     3.During the designing process of application, we will let you know about the other aspect of the application too. 

     4. Our Expert trainer will let you know about every in’s and out’s about the problem scenario.

Achieving your dream goal is our motto. Our excellent team is working restlessly for our students to click their target. So, believe on us and our advice, and we assured you about your sure success.

 

How to implement Bubble Sort in Python?

Introduction:

  1. As we know that the Python is more powerful language which offer great tools for data crunching and preparation, as well as for complex scientific data analysis and modelling. 

  2. Python has multiple implementations including Jython, scripted in Java language for Java Virtual Machine.

  3. Most of the Python modules work on community development model and are open-source and free.

  4. When we are going to use the python for programming approach, then there are several things we need to know.

  5. One of the important techniques is Sorting. In Sorting we are going to arrange the data in an increasing or decreasing order according to some linear relationship among the elements.

Here I am going to discuss about the working approach of Bubble sort. I am also going to discuss the step wise discussion as below.

What is Bubble sort?   

  1. The Bubble sort is the most common techniques which is being used for arranging the elements in either increasing or decreasing order. It is also known as sinking sort. 

  2. In this technique the list elements to be get sorted, are used to comparing each pair of adjacent items.

  3. During the comparison depending on the condition specified they are allowed to swap if they are not in the correct order.

  4. The above steps mentioned are repeated until no more swaps are needed. which is used to yield the final sorted list.

Steps for performing a Bubble Sort:

During the process of bubble sort, the following steps are used to arrange the elements. These steps are mentioned as below.

  1. In the beginning of the process, we need to pick the first and second element in the list compare and allow to get swap depending upon the condition specified if they are not in the correct order.

  2. The same processes of comparing to be done for second and third element and swap them if they are in the wrong order.

  3. Proceed similarly until the last element of the list in a similar fashion.

  4. Keep repeating all of the above steps until the list is sorted.

Bubble Sort Algorithm:

As we have already discussed above that the Bubble Sort is a sorting algorithm technique which is basically used to sort the list items in either ascending or descending order. If we need to arrange the elements of the list in ascending order then it can be done by comparing two adjacent values. 

During the process If we are going for ascending order then if the first value is higher than second value, then swapping will took place and the first value takes the second value position. Otherwise swapping will not takes place if the first element is lesser than the second value.

The basic algorithm used for such case is discussed below.

Step 1) At the first we need to get the total number of elements. Get the total number of items in the given list.

Step 2) We need to determine the number of outer passes (n - 1) to be done. If the number of elements in the list is n then it is the n-1.

Step 3) Here we need to perform the inner passes (n - 1) times for outer pass 1. During this process the first element is get compare with the second element and If the second value is less than the first value, then swap the positions.

Step 4) Repeat step 3 until we reach to the outer pass (n - 1). 

To understand the mechanism in better manner let us consider the following example as below.

Example:

Let us consider the list as 

A=[21,6,9,33,3]

Step-1: The values 21 and 6 are compared to check which one is greater than the other.

[21,6,9,33,3]

Since, the 21 is greater than 6, so 21 takes the position occupied by 6 while 6 takes the position that was occupied by 21. So now the new list will be 

[6, 21,9,33,3]

Step-2: The values 21 and 9 are compared.

[6, 21,9,33,3]

Here since, 21 is greater than 9, so we swap the positions of 21 and 9. So the new list will be 

[6,9, 21,33,3]

Step-3: The values 21 and 33 are compared to find the greater one.

 [6,9, 21,33,3]

Here since, The value 33 is greater than 21, so no swapping takes place.

Step-4: The values 33 and 3 are compared to find the greater one.

[6,9, 21,33,3]

Here The value 33 is greater than 3, so we swap their positions. So the new list is 

[6,9, 21,3,33]

The sorted list at the end of the first iteration is like the one above, But during the second iteration the new list is as follows

[6,9, 3,21,33]

After the third iteration the new list is as follows

[6,3,9,21,33]

After the forth iteration the new list is as follows

[3,6,9,21,33]

The above is the final sorted list.

Python Program to implement Bubble Sort:

def bubbleSort( theSeq ):
    n = len( theSeq )
    for i in range( n - 1 ) :
        flag = 0
for j in range(n - 1) :
            if theSeq[j] > theSeq[j + 1] : 
               tmp = theSeq[j]
                theSeq[j] = theSeq[j + 1]
               theSeq[j + 1] = tmp
flag = 1
        if flag == 0:
break
    return theSeq
el = [21,6,9,33,3] 
result = bubbleSort(el)
print (result)

In the above code, we compare the adjacent numbers and swap them if they are not in the correct order. 

Scope @ NareshIT:

  1. At Naresh IT you will get a good Experienced faculty who will guide you, mentor you and nurture you to achieve your dream goal.

  2. Here you will get a good hand on practice in terms of practical industry-oriented environment which will definitely help you a lot to shape your future.

  3. During the designing process of application, we will let you know about the other aspect of the application too. 

  4. Our Expert trainer will let you know about every in’s and out’s about the problem scenario.

Achieving your dream goal is our motto. Our excellent team is working restlessly for our students to click their target. So, believe on us and our advice, and we assured you about your sure success.