Data Types Category Page - PythonForBeginners.com https://www.pythonforbeginners.com Learn By Example Fri, 19 Nov 2021 20:19:35 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.13 https://www.pythonforbeginners.com/wp-content/uploads/2020/05/cropped-pfb_icon-32x32.png Data Types Category Page - PythonForBeginners.com https://www.pythonforbeginners.com 32 32 201782279 Namedtuple in Python https://www.pythonforbeginners.com/data-types/namedtuple-in-python Tue, 16 Nov 2021 15:16:04 +0000 https://www.pythonforbeginners.com/?p=9464 You must have used a tuple or a python dictionary in your program. Although they are very useful data structures, they have some drawbacks. In this we will study what is a namedtuple in python and how we can use it in place of a tuple or a dictionary. Problems with tuples and dictionaries Suppose […]

The post Namedtuple in Python appeared first on PythonForBeginners.com.

]]>
You must have used a tuple or a python dictionary in your program. Although they are very useful data structures, they have some drawbacks. In this we will study what is a namedtuple in python and how we can use it in place of a tuple or a dictionary.

Problems with tuples and dictionaries

Suppose you are working on creating a python application and you have to specify the color of the graphical interface. In such a case, you can use a tuple with (red, green, blue) value as follows.

color=(100,125,130)

But, here is a problem. Suppose your teammate reads your code and he doesn’t understand what the tuple in the above example signifies. It may be (red,green,blue) value or (hue, saturation, brightness) value according to him. To avoid such confusion, you can use a dictionary with red, green and blue as its key.

color={"red":100, "green":125, "blue": 130}

Again, when we are using a dictionary, we will have to create a dictionary for every component used in the graphical interface. This will make our code redundant and unreadable. To solve these issues, we can use a namedtuple in our python program. Let us discuss what it is and how we will use it.

What is a namedtuple in python?

You can think of a namedtuple as an intermediate data structure between a tuple and a dictionary. As the name suggests, a namedtuple in python is a tuple with named fields. Generally , we access the elements of a tuple using their indices. But in a namedtuple, we can specify the names of each index and then we can access the elements using the names. 

Let us discuss this in detail in the following sections.

How to create a namedtuple in Python?

Namedtuple has been defined in the collections module. You can import it as follows.

from collections import namedtuple

After importing the namedtuple module, you can create a namedtuple using the namedtuple() constructor.

The namedtuple() constructor takes the name of the object class to be created and their field names as input arguments. It then creates a subclass of tuple in which the fields are named. 

For example, we can define a “Color” namedtuple with field names as “red”,”green” and “blue” as follows.

Color = namedtuple("Color", ["red", "green", "blue"])

After defining the namedtuple subclass, we can create named tuples by giving the values for the fields as follows.

color=Color(100,125,130)

We can also access the value at different fields of a namedtuple using the attribute notation as follows.

from collections import namedtuple

Color = namedtuple("Color", ["red", "green", "blue"])
color = Color(100, 125, 130)

print("The namedtuple is:", color)
print("The red value is:", color.red)
print("The green value is:", color.green)
print("The blue value is:", color.blue)

Output:

The namedtuple is: Color(red=100, green=125, blue=130)
The red value is: 100
The green value is: 125
The blue value is: 130

If needed, you can also find the field names of a namedtuple. For this, you can use the _fields attribute that contains the field names as follows.

from collections import namedtuple

Color = namedtuple("Color", ["red", "green", "blue"])
color = Color(100, 125, 130)

print("The namedtuple is:", color)
print("The fields of the namedtuple are:", color._fields)

Output:

The namedtuple is: Color(red=100, green=125, blue=130)
The fields of the namedtuple are: ('red', 'green', 'blue')

Benefits of using a namedtuple in Python

There are several benefits of using namedtuples over tuples and dictionaries.

  • Unlike tuples, Namedtuples allow indexing as well as field names. This makes our code more understandable.
  • Unlike dictionaries, namedtuples are immutable and can be stored in a set. Also, Using a namedtuple instead of a dictionary requires us to write less code.
  • Despite having these advantages, namedtuples use almost similar memory compared to a tuple.

How to modify a namedtuple?

A namedtuple is a subclass of tuple and is considered to be immutable. It can be stored in a set and shows every property of immutable objects. But, we can modify the values in a namedtuple. For this, we can use the _replace() method that takes a keyword argument with the field name and new value. After that it returns the modified namedtuple as follows.

from collections import namedtuple

Color = namedtuple("Color", ["red", "green", "blue"])
color = Color(100, 125, 130)

print("The original namedtuple is:", color)
color = color._replace(red=200)
print("The modified namedtuple is:", color)

Output:

The original namedtuple is: Color(red=100, green=125, blue=130)
The modified namedtuple is: Color(red=200, green=125, blue=130)

Conclusion

In this article, we have discussed about namedtuple in python. We also discussed its use and benefits over tuples and dictionaries. To learn more about python programming, you can read this article on list comprehension. You may also like this article on the linked list in Python.

The post Namedtuple in Python appeared first on PythonForBeginners.com.

]]>
9464
Implement Stack in Python https://www.pythonforbeginners.com/data-types/implement-stack-in-python Tue, 20 Jul 2021 13:14:06 +0000 https://www.pythonforbeginners.com/?p=8765 Stack is a data structure which follows last in first out (LIFO) order for accessing the elements. In a stack, we can only access the most recently added element. Stacks have many uses in applications like expression handling, backtracking and function calls. In this article, we will try to implement stack data structure with linked […]

The post Implement Stack in Python appeared first on PythonForBeginners.com.

]]>
Stack is a data structure which follows last in first out (LIFO) order for accessing the elements. In a stack, we can only access the most recently added element. Stacks have many uses in applications like expression handling, backtracking and function calls. In this article, we will try to implement stack data structure with linked lists in python.

Implement stack in Python using linked list

A linked list is a linear data structure in which each data object points to one another. To implement a stack with linked list, we will have to perform insertion and deletion and deletion of elements from a linked list such that it takes a constant amount of time. This is only possible when we insert as well as delete the elements at the start of the linked list.

To implement a stack with linked list in python, we will first define a node object which will have the current element, will point to the node which was inserted just before it using a reference next. The Node can be implemented as follows in python.

class Node:
    def __init__(self,data,size):
        self.data=data
        self.next=None

When we implement a stack with linked list, it will have an element named top which will refer to the most recent element inserted in the linked list. All other  elements can be accessed with the help of that.We can implement an empty stack in python with top initialized to None and stackSize initialized to 0 as follows .

class Stack:
    def __init__(self):
        self.top=None
        self.stackSize=0

Implement Push operation in stack in Python

When we insert an element into the stack, the operation is called push operation. To implement push operation in stack with the help of linked list, for every insertion we will add the element to be inserted at the start of the linked list . In this way, the most recent element will always be at the start of the linked list. Then we will point the top element of the stack to the start of the linked list and increment the stackSize by 1. The push operation can be implemented using linked lists in python as follows.

 def push(self,data):
        temp=Node(data)
        if self.top is None:
            self.top=temp
            self.stackSize= self.stackSize+1
        else:
            temp.next=self.top
            self.top=temp
            self.stackSize=self.stackSize+1

Implement Pop operation in stack in Python

When we take out an element from the stack, the operation is said to be a pop operation. The element to be taken out from stack is the most recently added element to the stack. As we know that during a push operation, we add the most recent element to the start of the linked list which is pointed by the top of stack hence we will remove the element pointed by top and will point top to the next recent element. Before performing pop operation, we will check if stack is empty. If the stack is empty i.e. top points to None, we will raise an exception using python try except with a message that stack is empty. We can implement the pop operation as follows.

 def pop(self):
        try:
            if self.top == None:
                raise Exception("Stack is Empty")
            else:
                temp=self.top
                self.top=self.top.next
                tempdata=temp.data
                self.stackSize= self.stackSize-1
                del temp
                return tempdata
        except Exception as e:
            print(str(e))

How to access topmost element of stack

As the topmost element of the stack is being referenced by top, we just have to return the data in the node pointed by top. It can be implemented as follows.

def top_element(self):
        try:
            if self.top == None:
                raise Exception("Stack is Empty")
            else:
                return self.top.data
        except Exception as e:
            print(str(e))

Get the size of the stack

As we keep the current size of stack in stackSize variable, we just have to return the value in the stackSize variable top. This can be done as follows.

def size(self):
        return self.stackSize

Check if the stack is empty

The element top refers to the most recent element in the stack. If there is no element in the stack, top will point to None. Thus, to check if the stack is empty, we just have to check if top points to None or stackSize variable has a value 0. We can implement isEmpty() method to check if the stack is empty as follows.

def isEmpty(self):
        if self.stackSize==0:
            return True
        else:
            return False

The full working code to implement stack using linked list in python is as follows.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 25 00:28:19 2021

@author: aditya1117
"""

class Node:
    def __init__(self,data):
        self.data=data
        self.next=None
class Stack:
    def __init__(self):
        self.top=None
        self.stackSize=0
    def push(self,data):
        temp=Node(data)
        if self.top is None:
            self.top=temp
            self.stackSize= self.stackSize+1
        else:
            temp.next=self.top
            self.top=temp
            self.stackSize=self.stackSize+1
    def pop(self):
        try:
            if self.top == None:
                raise Exception("Stack is Empty")
            else:
                temp=self.top
                self.top=self.top.next
                tempdata=temp.data
                self.stackSize= self.stackSize-1
                del temp
                return tempdata
        except Exception as e:
            print(str(e))
    def isEmpty(self):
        if self.stackSize==0:
            return True
        else:
            return False
    def size(self):
        return self.stackSize
    def top_element(self):
        try:
            if self.top == None:
                raise Exception("Stack is Empty")
            else:
                return self.top.data
        except Exception as e:
            print(str(e))
s=Stack()
s.push(1)
print(s.size())

s.push(2)
print(s.size())

print(s.pop())
print(s.size())
print(s.pop())
print(s.stackSize)

print(s.top_element())
print(s.isEmpty())

Output:

1
2
2
1
1
0
Stack is Empty
None
True

Conclusion

In this article, we have implemented stack and all its operations using linked list in python. To gain more insight into it and understand how stack is different from inbuilt data structures like python dictionary, list and set , copy the full code given in the above example and experiment with the operations in it. Stay tuned for more informative articles.

The post Implement Stack in Python appeared first on PythonForBeginners.com.

]]>
8765
Bytearray in Python https://www.pythonforbeginners.com/data-types/bytearray-in-python Thu, 08 Jul 2021 14:17:53 +0000 https://www.pythonforbeginners.com/?p=8966 You must have studied different data types in python such as strings and numeric data types like integers and floating point numbers. In this article you will learn about another data type called bytearray in python programming language. You will study the underlying concepts behind bytearray in python and will implement different types of operations […]

The post Bytearray in Python appeared first on PythonForBeginners.com.

]]>
You must have studied different data types in python such as strings and numeric data types like integers and floating point numbers. In this article you will learn about another data type called bytearray in python programming language. You will study the underlying concepts behind bytearray in python and will implement different types of operations on bytearray objects to understand the concepts.

What is bytearray in Python?

A bytearray in python is an array of bytes that can hold data in a machine readable format. When any data is saved  in the secondary storage, it is encoded according to a certain type of encoding such as ASCII, UTF-8 and UTF-16 for strings, PNG, JPG and JPEG for images and mp3 and wav for audio files and is turned into a byte object. When we access the data again using python read file operation, it is decoded into the corresponding text, image or audio. Thus byte objects contain data that are machine readable and bytearray objects are arrays of bytes.

How to create bytearray objects in Python?

We can create a bytearray object in python using  bytearray() method. The bytearray() function takes three parameters as input all of which are optional. The object which has to be converted to bytearray is passed as the first parameter. Second and third parameters are used only when the first parameter is  string. In this case, the second parameter is the encoding format of the string and the third parameter is the name of the error response which is executed when the encoding fails. The bytearray() function returns a bytearray object. In the next sections, we will understand the working of bytearray() function by creating bytes objects from different data objects.

Create a bytearray object

To create a bytearray object of a given size, we can give the desired size of bytearray as input to the bytearray() function. After successful execution, it returns the bytearray object of given size initialized to zeros as follows.

myObj=bytearray(10)
print("The bytearray object is:",myObj)
print("Length of the bytearray object is:",len(myObj))

Output:

The bytearray object is: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
Length of the bytearray object is: 10

To convert a string to bytearray object, we pass the string as first input and encoding type as second input argument to the bytearray() function. It then returns the bytearray of string as follows.

myString="pythonforbeginners.com"
print("The string is:",myString)
myObj=bytearray(myString,"UTF-8")
print("The bytearray object is:",myObj)

Output:

The string is: pythonforbeginners.com
The bytearray object is: bytearray(b'pythonforbeginners.com')

We can convert a list of integers to bytearray using bytearray() function in python. The bytearray() function takes the list of integers between 0 and 255 as input and returns the corresponding bytearray object as follows.

myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)

Output:

The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')

For integer values which are not between 0 to 255, the bytearray function raises ValueError as follows.

myList=[1,2,56,78,900]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/main.py", line 3, in <module>
    myObj=bytearray(myList)
ValueError: byte must be in range(0, 256)
The List is: [1, 2, 56, 78, 900]

We can handle the above exception using python try-except as follows.

myList=[1,2,56,78,900]
print("The List is:",myList)
try:
    myObj=bytearray(myList)
    print("The bytearray object is:",myObj)
except Exception as e:
    print(str(e))

Output:

The List is: [1, 2, 56, 78, 900]
byte must be in range(0, 256)

Operations on bytearray objects

Although byte objects are immutable, bytearray objects are mutable and can be modified and they almost behave as python lists. Following are some common operations on bytearray objects.

Bytearray supports indexing and slicing. We can use indices to get the data at a particular index or we can slice a bytearray to get data between two indices as follows.

myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
sliced_obj=myObj[0:2]
indexed_obj=myObj[1]
print("Sliced part of bytearray is:",sliced_obj)
print("Data at index 1 of bytearray is:",indexed_obj)

Output:

The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
Sliced part of bytearray is: bytearray(b'\x01\x02')
Data at index 1 of bytearray is: 2

As bytearray objects are mutable, we can also modify the bytearray objects using indexing and slicing as follows.

myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
myObj[0:2]=[15,16]
myObj[4]=34
print("The modified bytearray object is:",myObj)

Output:

The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x0f\x108N"')

We can also insert data into a bytearray object at a given index using insert() method as follows.

myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
myObj.insert(1,23)
print("The modified bytearray object is:",myObj)

Output:

The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x01\x17\x028NZ')

We can append data into a bytearray object using the append() method as follows.

myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
myObj.append(105)
print("The modified bytearray object is:",myObj)

Output:

The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x01\x028NZi')

We can also delete data at a specific index or between two indices using del statement as follows.

myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
del myObj[0]
del myObj[1:3]
print("The modified bytearray object is:",myObj)

Output:

The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x02Z')

Conclusion

In this article, we have studied the bytearray data structure in python. We have also converted different data types to bytearray and have performed operations like appending data to a bytearray, insertion of data and deletion of data from a bytearray using built in functions.Stay tuned for more informative articles.

The post Bytearray in Python appeared first on PythonForBeginners.com.

]]>
8966
Complex numbers in Python https://www.pythonforbeginners.com/data-types/complex-numbers-in-python Tue, 22 Jun 2021 14:31:31 +0000 https://www.pythonforbeginners.com/?p=8889 While working on data science, machine learning or scientific calculations, we often need to perform calculations on numeric data types including  complex numbers. In this article, we will learn how to define and use complex numbers in python.  What is a complex number ? A complex number is a number that can be written in […]

The post Complex numbers in Python appeared first on PythonForBeginners.com.

]]>
While working on data science, machine learning or scientific calculations, we often need to perform calculations on numeric data types including  complex numbers. In this article, we will learn how to define and use complex numbers in python. 

What is a complex number ?

A complex number is a number that can be written in the form of (a+b j) where a and b are real numbers. Here j is an imaginary number and is defined to be the square root of -1. Complex numbers occur in pairs and are mostly used in calculations involving square roots of negative numbers.

How to define complex numbers in Python?

We can define complex numbers in python by simply declaring a variable and assigning an expression of the form (a+bj) .Here “a” and “b” should be a numeric literal and “j” can be any alphabet character. We can also check the data type of the defined variable using type() function as follows.

myNum= 3+2j
print("The Number is:")
print(myNum)
print("Data type of Number is:")
print(type(myNum))

Output:

The Number is:
(3+2j)
Data type of Number is:
<class 'complex'>

We can also define a complex number using complex() function. The complex function takes a compulsory input as first parameter which denotes the real part of the complex number and an optional input as second parameter which denotes the imaginary part of the complex number. We can define a complex number using the complex() function as follows.

myNum= complex(3,2)
print("The Number is:")
print(myNum)
print("Data type of Number is:")
print(type(myNum))

Output:

The Number is:
(3+2j)
Data type of Number is:
<class 'complex'>

Extracting real and imaginary part of a complex number

In a complex number (a+b j), “a” is called the real part and “b” is called the imaginary part. We can extract real part of the complex number using an attribute named “real” which contains value “a” and imaginary part using the attribute “imag” which contains the value “b” as follows.

myNum= complex(3,2)
print("The Complex Number is:")
print(myNum)
print("Real part of the complex Number is:")
print(myNum.real)
print("Imaginary part of the complex Number is:")
print(myNum.imag)

Output:


The Complex Number is:
(3+2j)
Real part of the complex Number is:
3.0
Imaginary part of the complex Number is:
2.0

Conjugate of a complex number in Python

For a complex number (a+ b j), its conjugate is defined as the complex number (a- b j).We can obtain the conjugate of any complex number in python using the conjugate() method. The conjugate() method when invoked on a complex number, returns the complex conjugate of the number. This can be done as follows.

myNum= complex(3,2)
print("The Complex Number is:")
print(myNum)
print("Conjugate of the complex Number is:")
print(myNum.conjugate())

Output:

The Complex Number is:
(3+2j)
Conjugate of the complex Number is:
(3-2j)

Magnitude of the complex number

The magnitude of a complex number (a+b j) is the distance of the point (a,b) from (0,0). It is the length of the vector which represents the complex number. The magnitude of a complex number can be calculated as follows in python.

import math
def magnitude(num):
    x=num.real
    y=num.imag
    mag=x*x+y*y
    return math.sqrt(mag)
myNum= complex(3,2)
print("The Complex Number is:")
print(myNum)
print("Magnitude of the complex Number is:")
print(magnitude(myNum))

Output:

The Complex Number is:
(3+2j)
Magnitude of the complex Number is:
3.605551275463989

Conclusion

In this article, we have studied the basics of complex numbers and its attributes in python. We have also derived the real part, imaginary part , conjugate and magnitude of a complex number. We can also write the programs used in this article with exception handling using python try except to make the programs more robust and handle errors in a systematic way. Stay tuned for more informative articles.

The post Complex numbers in Python appeared first on PythonForBeginners.com.

]]>
8889
Copy in Python https://www.pythonforbeginners.com/data-types/copy-in-python Thu, 20 May 2021 13:11:19 +0000 https://www.pythonforbeginners.com/?p=8694 In python programs, several times we need to have an identical copy of an existing data. For simple data types like int, float, boolean values or string, an assignment operation does the task for us as they are immutable data types. After copying, when we make  any changes to any variable with immutable data types, […]

The post Copy in Python appeared first on PythonForBeginners.com.

]]>
In python programs, several times we need to have an identical copy of an existing data. For simple data types like int, float, boolean values or string, an assignment operation does the task for us as they are immutable data types. After copying, when we make  any changes to any variable with immutable data types, a new instance of data is created and they don’t affect the original data. In case of mutable data types like list or dictionary, If we use an assignment operator to copy the data to another variable, both the variables refer to the same data object and if we make changes to any of the variables, the object gets changed reflecting the effect on both the variables. In this article, we will try to understand this concept of copy in python with examples.

How to get the object ID of an object in python?

To illustrate the concept of copy in python, we will need to know the object ID of an object. For this task, we will use the id() function. This function takes the variable name as input and returns a unique id for the object. This can be seen from the following example.

var1=1
print("ID of object at which var1 refers:",end=" ")
print(id(var1))

Output:

ID of object at which var1 refers: 9784896

Copy an object using = operator in python

When we try to copy an object using = operator by assigning a variable to another, it doesn’t create a new object but both the variables are assigned to the same object. 

For example, if we have a variable named var1 referring to an object and we assign var1 to var2 by the statement var2=var1, both the variables point to the same object and thus will have the same ID. This can be seen as follows.


var1=11
var2=var1
print("ID of object at which var1 refers:",end=" ")
print(id(var1))
print("ID of object at which var2 refers:", end=" ")
print(id(var2))

Output:

ID of object at which var1 refers: 9785216
ID of object at which var2 refers: 9785216

 For immutable objects, when we change the value assigned to any of var1 or var2, a new object is created for the newly assigned value to the variable. So, if we change the value assigned to var2, a new object will be created and after reassignment, var1 and var2 will refer to objects with different object ID. This can be understood as follows.

var1=11
var2=var1
print("ID of object at which var1 refers:",end=" ")
print(id(var1))
print("ID of object at which var2 refers:", end=" ")
print(id(var2))
print("After Assigning value to var2")
var2=10
print("ID of object at which var1 refers:",end=" ")
print(id(var1))
print("ID of object at which var2 refers:", end=" ")
print(id(var2))

Output:

ID of object at which var1 refers: 9785216
ID of object at which var2 refers: 9785216
After Assigning value to var2
ID of object at which var1 refers: 9785216
ID of object at which var2 refers: 9785184

Unlike above, if we are copying mutable objects like lists, they point to the same object after reassignment and modification using any variable leads to change in the same object. This can be seen as follows.


list1=[1,2,3]
list2=list1
print("ID of object at which list1 refers:",end=" ")
print(id(list1))
print("ID of object at which list2 refers:", end=" ")
print(id(list2))
print("After appending another value to list2")
list2.append(4)
print("ID of object at which var1 refers:",end=" ")
print(id(list1))
print("ID of object at which var2 refers:", end=" ")
print(id(list2))

Output:

ID of object at which list1 refers: 140076637998720
ID of object at which list2 refers: 140076637998720
After appending another value to list2
ID of object at which var1 refers: 140076637998720
ID of object at which var2 refers: 140076637998720

In the above output, we can see that when we use an assignment operator to copy list, both the variables list1 and list2 refer to same object and have same ID. This doesn’t change when we make changes to any of the list.

How to copy mutable objects in Python?

For copying mutable objects like lists or dictionaries, we use copy() method.

When invoked on any object, the copy() method creates a new object with the same data as the original object and returns a reference to it. It means that when we copy  the objects using the copy() method instead of = operator, the address of the original object and copied object are different.

For example if we copy list1 to list2 using the copy() method then list1 and list2 will refer to different objects. This can be seen as follows.

list1=[1,2,3]
list2=list1.copy()
print("ID of object at which list1 refers:",end=" ")
print(id(list1))
print("ID of object at which list2 refers:", end=" ")
print(id(list2))

print("After appending another value to list2")
list2.append(4)
print("ID of object at which var1 refers:",end=" ")
print(id(list1))
print("ID of object at which var2 refers:", end=" ")
print(id(list2))

Output:

ID of object at which list1 refers: 140076492253376
ID of object at which list2 refers: 140076483798272
After appending another value to list2
ID of object at which var1 refers: 140076492253376
ID of object at which var2 refers: 140076483798272

In the output, It can be seen that list2 has a different object ID than list1. If we modify any values in list1, it will not cause any change to list2 which is not the case when we use = operator to copy an object to another.

Conclusion

In this article, we have studied about how to copy mutable and immutable objects in python. For immutable objects, we can use = operator because at each reassignment, a new object is created for immutable objects. In case of mutable objects like python dictionary, we should use the copy() method to copy an object like a list or dictionary to avoid unwanted errors in the program.We can also write the programs used in this article with exception handling using python try except to make the programs more robust and handle errors in a systematic way. Stay tuned for more informative articles.

The post Copy in Python appeared first on PythonForBeginners.com.

]]>
8694
Stack in Python https://www.pythonforbeginners.com/data-types/stack-in-python Thu, 29 Apr 2021 13:15:48 +0000 https://www.pythonforbeginners.com/?p=8756 In python, there are inbuilt data structures like list,tuple, set and dictionary but we may need some additional  functionalities in python programs. For example, If we need a last in first out (LIFO) functionality in our program then none of the inbuilt data structures provide that functionality. We can use stack to implement last in […]

The post Stack in Python appeared first on PythonForBeginners.com.

]]>
In python, there are inbuilt data structures like list,tuple, set and dictionary but we may need some additional  functionalities in python programs. For example, If we need a last in first out (LIFO) functionality in our program then none of the inbuilt data structures provide that functionality. We can use stack to implement last in first out functionality in python. In this article, we will study the concept behind stack data structure and implement it in python.

What is a stack?

A stack is a linear data structure in which we can only access or remove the element which was added last to it. In real life, we can take the example of a stack of plates where we can only take out the uppermost plate because it was added last. We can perform the following operations on a stack data structure in python.

  1. Insert an element(Push an element)
  2. Remove an element (Pop an element)
  3. Check if the stack is empty
  4. Check the topmost element in the stack
  5. Check the size of the stack

In the following subsections, we will implement stack and all its and will implement them in python. 

How to implement stack in python?

In this tutorial,we will define a class named Stack and will implement the Stack using python lists. In the Stack class, we will have a list for containing the data added to the Stack and a variable for storing the size of the Stack. All the operations like push, pop, checking the size of the stack,checking the topmost element of stack and checking the stack if it is empty will be executed in constant time and thus will have O(1) time complexity. The Stack class will be defined as follows.The stackList is initialized as an empty list and stackSize is initialized to 0.

class Stack:
    def __init__(self):
        self.stackList=[]
        self.stackSize=0

Push items to a stack in python

To insert an item into the stack i.e. to push an element into the stack, we will simply append the element in the list and then we will increment the stackSize variable by 1. To implement the operation, we define a method which takes the element as an argument and appends the element to the list in the stack. Then it increments the stackSize variable. Following is the implementation for the push() method.

def push(self,item):
        self.stackList.append(item)
        self.stackSize+=1

Pop items from a stack in python

To remove an item from the stack i.e. to pop an element from the stack, we have to remove the element from the stack which was added last to it. As we append the element to the list in stack while push operation, the last element in the list will be the most recent element and will be removed from the stack. So we simply delete the last element from the list. 

To implement the pop operation, we will implement the pop() method which first checks if the number of elements in the stack is greater than 0. If yes, then it will remove the last element from the list and decrease the stackSize by 1. If the number of elements in stack is 0, it will show an error message saying that the list is empty. For this task, we will use exception handling using python try except to raise an exception when the size of stack is 0. The pop() method can be implemented as follows.

def pop(self):
        try:
            if self.stackSize==0:
                raise Exception("Stack is Empty, returning None")
            temp=self.stackList.pop()
            self.stackSize-=1
            return temp
        except Exception as e:
            print(str(e))

Check size of the stack

To check the size of the stack, we simply have to check the value of the stackSize variable. For this operation, we will implement the size() method which returns the value of stackSize variable as follows.

def size(self):
        return self.stackSize

Check if stack is empty

To check if the stack has no elements i.e it is empty, we will have to check if the stackSize variable is 0 or not. For this operation, we will implement the isEmpty() method which returns True if the stackSize variable is 0 and returns false otherwise. Following is the implementation for isEmpty() method.

def isEmpty(self):
        if self.stackSize==0:
            return True
        else:
            return False

Check topmost element of an stack

The topmost element of the stack will be the element most recently added to it. To check the topmost element of the stack, we just have to return the last element in the list in the stack. For this operation, we will implement the top() method which first checks if the stack is empty i.e. stackSize is 0 or not, if yes then it will print a message saying that the stack is empty. Otherwise it will return the last element of the list. This can be implemented as follows.

def top(self):
        try:
            if self.stackSize==0:
                raise Exception("Stack is Empty, returning None")
            return self.stackList[-1]
        except Exception as e:
            print(str(e))

The complete working code for implementing stack in python is follows.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 19:38:55 2021

@author: aditya1117
"""

class Stack:
    def __init__(self):
        self.stackList=[]
        self.stackSize=0
    def push(self,item):
        self.stackList.append(item)
        self.stackSize+=1
    def pop(self):
        try:
            if self.stackSize==0:
                raise Exception("Stack is Empty, returning None")
            temp=self.stackList.pop()
            self.stackSize-=1
            return temp
        except Exception as e:
            print(str(e))
    def size(self):
        return self.stackSize
    def isEmpty(self):
        if self.stackSize==0:
            return True
        else:
            return False
    def top(self):
        try:
            if self.stackSize==0:
                raise Exception("Stack is Empty, returning None")
            return self.stackList[-1]
        except Exception as e:
            print(str(e))
            
#Execution
s=Stack()
#push element
s.push(1)
#push element
s.push(2)
#push element
s.push(3)
print("popped element is:")
print(s.pop())
#push an element
s.push(4)
print("topmost element is:")
print(s.top())

Output:

popped element is:
3
topmost element is:
4

Conclusion

In this article, we have studied and implemented stack data structure in python. We have seen the operation for the stack and you may find it very different from python dictionary, list, set e.t.c. Stacks are used extensively in real world applications like expression handling, backtracking, function calls and many other operations and you should have a working knowledge about it. Stay tuned for more informative articles.   

The post Stack in Python appeared first on PythonForBeginners.com.

]]>
8756
Python : More Dictionarys https://www.pythonforbeginners.com/dictionary/python-more-dictionarys Wed, 03 Oct 2012 01:04:15 +0000 https://www.pythonforbeginners.com/?p=1140 What is a Dictionary? Dictionaries are collections of items that have a “key” and a “value”. Dictionaries are mutable. You do not have to reassign the dictionary to make changes to it. They are just like lists, except instead of having an assigned index number, you make up the index: Example 1 testList = ["first", […]

The post Python : More Dictionarys appeared first on PythonForBeginners.com.

]]>
What is a Dictionary?

Dictionaries are collections of items that have a “key” and a “value”.

Dictionaries are mutable. You do not have to reassign the dictionary to make
changes to it.

They are just like lists, except instead of having an assigned index number,
you make up the index:

Example 1

testList = ["first", "second", "third"]
testDict = {0:"first", 1:"second", 2:"third"} 

A dictionary in Python is enclosed by {}, and to create one you have to provide a key / value.

Each key in the dictionary must be unique.

A colon is placed between key and value (key:value)

Each key:value pair is separated by a comma

Example 2

>> phonenumbers = {'Jack':'555-555', 'Jill':'555-556'} 

phonebook = {}
phonebook["Jack"] = "555-555"
phonebook["Jill"] = "555-556"

print phonebook
{'Jill': '555-556', 'Jack': '555-555'}

Dictionaries only work one way, to get a value out of a dictionary,you MUST enter the key.

You cannot provide the value and get the key.

Example 3

phonebook = {}
phonebook["Jack"] = "555-555"
phonebook["Jill"] = "555-556"

print phonebook['Jill']
555-556

Key / Value Usage


To add a key / value pair in a dictionary
>>phonebook["Matt"] = "555-557"

To change a key / value pair:
>>phonebook["Jack"] = '555-558'

To remove a key / value pair, use del
 >>del phonebook["Jill"]
    
To see if a key exists, use has_key() method
>>phonebook.has_key("Matt")
    
To copy whole dictionary, use the copy() method
phonebook2 = phonebook.copy() 

I mostly use dictionarys when storing results for lookups.

The post Python : More Dictionarys appeared first on PythonForBeginners.com.

]]>
1140
Python Join Examples https://www.pythonforbeginners.com/code-snippets-source-code/python-join-examples Thu, 20 Sep 2012 07:35:41 +0000 https://www.pythonforbeginners.com/?p=451 Overview This post will show some examples of the Python join method. What is important to remember is that the character that joins the elements is the one upon which the function is called. Join Examples Let’s show an example Creating a new list >>> music = ["Abba","Rolling Stones","Black Sabbath","Metallica"] >>> print music ['Abba', 'Rolling […]

The post Python Join Examples appeared first on PythonForBeginners.com.

]]>
Overview

This post will show some examples of the Python join method.

What is important to remember is that the character that joins the elements
is the one upon which the function is called.

Join Examples

Let’s show an example

Creating a new list

>>> music = ["Abba","Rolling Stones","Black Sabbath","Metallica"]

>>> print music
['Abba', 'Rolling Stones', 'Black Sabbath', 'Metallica']

Join a list with an empty space

>>> print ' '.join(music)
Abba Rolling Stones Black Sabbath Metallica

Join a list with a new line

>>> print "
".join(music)
Abba
Rolling Stones
Black Sabbath
Metallica

Join a list with a tab

>>> print "	".join(music)
Abba	Rolling Stones	Black Sabbath	Metallica
>>> 

Happy scripting!

The post Python Join Examples appeared first on PythonForBeginners.com.

]]>
451