Blogs  

What is the use of self 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 today has multiple implementations including Jython, scripted in Java language for Java Virtual Machine.

  3. IronPython is the new variety which is written in C# for the Common Language Infrastructure, and PyPy version written in RPython and translated into C. 

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

What is the use of self in Python?

 

  1. In Python the self is used to represent the instance of the class. 

  2. Using this keyword, we can be able to access the attributes and methods of the class.

  3. It is also used for binding the attributes with the given arguments. 

  4. It is more often called as self because the Python does not use the '@' syntax to refer to instance attributes.

  5. Here in Python, if we need to access the methods which is used to passed the instances value automatically then we can use this technique.

  6. This method does not used to receive the values of the instances automatically.

Let us consider the following example below which will let you know about the use of self in detailed manner.

Here I am going to write the example which is best support for Python 3.

Example:

class car(): 

      

    # init method or constructor 

    def __init__(self, model, color): 

        self.model = model

 self.color = color 

          

    def show(self): 

        print("Model is", self.model ) 

        print("color is", self.color ) 

          

# both objects have different self which contain their attributes 

audi = car("audi a4", "blue") 

ferrari = car("ferrari 488", "green") 

  

audi.show()     # same output as car.show(audi) 

ferrari.show()  # same output as car.show(ferrari) 

Note: 

 

  1. It should be get noted that here Behind the scenes, in every instance method call, the Python is used to sends the instances also. 

  2. The Self is a convention and not a real python keyword. 

  3. The self is just a parameter in function like other parameters and if the user need then they are allowed to use another parameter name in place of it if they want.

  4. But as per the convention it is advisable and recommended  to use self because if we are going to use the self in the coding then it increase the readability of code.

Here I am going to write the example which is best support for Python 3.

Example:

class this_is_class:  

    def show(in_place_of_self):  

        print("we have used another " "parameter name in place of self")  

          

object = this_is_class()  

object.show() 

 Python class self-Constructor:

As you know that the Python released version 3.0 which is also called as Python 3 on December 2008. Technically this version was mainly released in order to fix the major problems which are get found in Python 2. As you know that the Python 3 was incompatible with Python 2 in many aspects. It is backward incompatible and Some features of Python 3 have been backported to Python 2.x versions to make the migration process easy in Python 3.

  1. Constructors are generally used for instantiating an object.

  2. It is mainly used  to initialize(assign values) to the data members of the class.

  3. When an object of class is created then the members are to be get initialised using the constructor.

  4. In Python the __init__() method is called the constructor and is always called when an object is created.

Let us consider the following example which will let you know how the zip function is get applied in Python3.

Syntax:

def __init__(self):

    # body of the constructor

Example:

 

class Person: 

  

    # default constructor 

    def __init__(self): 

        self.name = "Smith"

   # a method for printing data members 

    def print_name(self): 

        print(self.name)

# creating object of the class 

obj = Smith() 

  

# calling the instance method using the object obj 

obj.print_name()

 

Is self in Python a Keyword?

As we have already discussed earlier above that the self is basically used in different places as a parameter to a function. But it is not a keyword.

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 the linked list in Python

Introduction:

As we have already discussed earlier 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. Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is basically used for:

  • web application development (server-side),

  • software development,

  • mathematics,

  • system scripting.

Being the programmer in python Everyone should know about linked lists and its operation. A python developer should know how to create and implement the variety of linked list in practical manner. Here I am going to discuss the various ways of implementing the linked list in python using the suitable methods. 

Most of the programmer during the programming always come across a common question such as, “Does Python have a built-in or ‘native’ linked list data structure?” or, “How do I write a linked list in Python?”. Here I am going to discuss the various approaches in detail.

  1. The Python language doesn’t ship with a built-in linked list data type in the “classical” sense. 

  2. The Python’s list type is implemented as a dynamic array as it has the concept of list, tuple and dictionary.

  3. So we need here a typical scenarios to use a “proper” linked list data structure for performance reasons.

What is Linked List? And What are their characteristics?

A linked list is mainly defined as an ordered collection of values. In python the list is used to be get created in similar way like other programming language. In python  the Linked lists are get created in similar to arrays in the sense that they contain objects in a linear order. But they are get differ from traditional arrays approach in their memory layout.

The link list is a sequence of nodes having a similar data type, each node contains one data object and pointer to the next node.

A linked list is a linear data structure with the collection of multiple nodes. Where each element stores its own data and a pointer to the location of the next element. The last link in a linked list points to null, indicating the end of the chain. An element in a linked list is called a node. The first node is called the head. The last node is called the tail.

As we know that the Arrays are contiguous data structures which stores the similar kind of element under a single name  and they’re composed of fixed-size data records stored in adjoining blocks of memory.

The arrangement of the array is looks like as showed below.

Array Visualization

In the similar way the Linked lists is also get created.  The linked list are made up of data records linked together by pointers. This means that the data records that hold the actual “data payload” can be stored anywhere in memory. The following diagram showed below shows the  implementation scenario of linked list.

Linked List Visualization

There are two different kinds of linked lists: singly-linked lists and doubly-linked lists. The diagram showed above is the singly-linked list where each element in it has a reference to (a “pointer”) to the next element in the list.

Where as in a doubly-linked list, each element has a reference to both the next and the previous element. Why is this useful? Having a reference to the previous element can speed up some operations, like removing (“unlinking”) an element from a list or traversing the list in reverse order.

As you know that the Python 3.6 (CPython), doesn’t able to provide a dedicated linked list data type. 

Python does however include the collections.deque class which provides a double-ended queue and is implemented as a doubly-linked list internally. 

Now the main question get arises that how to create and write the linked list program in python. Here I am going to discuss below.

How to write a linked list program using Python?

If you want to stick with functionality built into the core language and into the Python standard library you have two options for implementing a linked list:

  • You could either use the collections.deque class from the Python standard library and take advantage of the fact that it’s implemented as a doubly-linked list behind the scenes. 

  • Alternatively, you could define your own linked list type in Python by writing it from scratch using other built-in data types. You’d implement your own custom linked list class or base your implementation of Lisp-style chains of tuple objects.

Implementing a Linked List

For creating a Linked List, we create a node object and create another class to use this node object.
Code for creating Node class.
The above program creates a linked list with three data elements.

class Node(object):

# Constructor to initilize class variables

def __init__(self, data=None, next_node=None):

self.data = data

self.next_node = next_node

#get data

def get_data(self):

return self.data

# get next value

def get_next(self):

return self.next_node

# set next data

def set_next(self, new_next):

self.next_node = new_next

When we are going to implement  the linked list then the Implementation of link list consists of the following

functionality in a linked list
1. Insert: This method is basically used to insert a new node in an existing linked list.
2. Size: This method is basically used to return the size of the linked list that how many elements does it contains.
3. Search: This method will return a node containing the data, else will raise an error
4. Delete: This method will delete a node containing the data, else will raise an error

Init method in a linked list:

This method is basically used to initialised the list with initial value. The code is as showed below.

class LinkedList(object):

def __init__(self, head=None):

self.head = head

Insertion of element into the linked list:

To insert the code into the linked list we need to use the following code. The segment of the program is as discussed below.

def insert(self, data):

new_node = Node(data) 

new_node.set_next(self.head) 

self.head = new_node

Predicting the Size of the list:

The following code is used to return the size of the list.

# Returns total numbers of node in list

def size(self):

current = self.head

count = 0

while current:

count += 1

current = current.get_next()

return count

Search the element form the list:

# Returns the node in list having nodeData, error occured if node not present

def search(self, nodeData):

current = self.head

isPresent = False

while current and isPresent is False:

if current.get_data() == nodeData:

isPresent = True

else:

current = current.get_next()

if current is None:

raise ValueError("Data not present in list")

return current

Delete the existing element from the list:

# Remove the node from linked list returns error if node not present

def delete(self, nodeData):

current = self.head

previous = None

isPresent = False

while current and isPresent is False:

if current.get_data() == nodeData:

isPresent = True

else:

previous = current

current = current.get_next()

if current is None:

raise ValueError("Data not present in list")

if previous is None:

self.head = current.get_next()

else:

previous.set_next(current.get_next())

When we are going to implement the delete method  it is used to traverses the list in the same way that search does, but in addition to keeping track of the current node, the delete method also remembers the last node is visited. When delete finally arrives at the node it wants to delete. It simply removes that node from the chain by “leapfrogging” it.

Python Linked Lists: Recap & Recommendations

We just looked at a number of approaches to implement a list in Python. You also saw some code examples of the standard operations and algorithms, for example how to reverse a linked list in-place.

You should only consider using a linked list in Python when you’ve determined that you absolutely need a linked data structure for performance reasons (or you’ve been asked to use one in a coding interview.)

In many cases the same algorithm implemented on top of Python’s highly optimized list objects will be sufficiently fast. If you know a dynamic array won’t cut it and you need a linked list, then check first if you can take advantage of Python’s built-in deque class.

Scope @ NareshIT:

  1. At NareshIT’s Python application Development program you will be able to get the extensive hands-on training in front-end, middleware, and back-end technology.

  2. It skilled you along with phase-end and capstone projects based on real business scenarios.

  3. Here you learn the concepts from leading industry experts with content structured to ensure industrial relevance.

  4. An end-to-end application with exciting features

 

Top 100 Python Interview Questions You Must Prepare

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. The Python frameworks are allows you to carry out complex mathematical computations and create sophisticated models that make sense of your data. Based on that you need to prepare yourself accordingly if you need to be a good Python Developer.

Why we should go for Python:

  1. As the Python is already a proven language in the data science industry and it is widely accepted by most of the industry, so it is now taken the lead as the toolkit for scientific data analysis and modelling. 

  2. These are open-sourced libraries, offering alternate ways of deriving the same output. 

  3. As the technology now a days gets more and more competitive, data scientists and engineers are continually striving for ways to process information, extract insights and model, by processing massive datasets. 

  4. Python is the only platform where we can be able to explore the various, so you need to be well versed in the various Python libraries that support your data science tasks and the benefits they offer to make your outputs more robust and speedier.

Here I would like to discuss the some important interview Questions on python and its related areas which is mostly required by the candidates to prepare who are willing to appear for Python developer.

Basic Interview Questions:

1. In python environment what is the difference between list and tuples in Python?
2. What are the key features of Python?
3. What type of language is python does belong?
4. How the Python is considered as an interpreted language?
5. What is pep 8 concepts in python? How will you relate it?
6. How the memory management is done in Python?
7. What is name space in Python?
8. What is PYTHON PATH?
9. What are python modules?
10. What are local variables and global variables in Python?

11. What are negative indexes and why are they used?

12. What are Python packages?

13.How can files be deleted in Python?

14. What are the built-in types of python?

15. What advantages do NumPy arrays offer over (nested) Python lists?

16. How to add values to a python array?

17. How to remove values to a python array?

18. Does Python have OOps concepts fully supported? If yes then how?

19. What is the difference between deep and shallow copy in python? Explain with suitable syntax?

20. Is python case sensitive language like other languages?

21.What is type conversion in Python? Explain with suitable approach?

22. How to install Python on Windows and set path variable?

23. What do you mean by the term “indentation”? Is it required in python?

24. What is the difference between Arrays, Tuple and lists? Discuss?

25. What are functions in Python? Explain the importance of function in python?

26.What is “init” in python? Explain with suitable syntax?

27.What is a lambda function? What is the main utility of Lambda in python?

28. What do you mean by the term “self-Python”? Explain?

Basic Python Programs based questions:

1. Write a program in Python to execute the Bubble sort, selection sort algorithm.

2. Write a program in Python to produce pascal triangle.

3. Write a program to produce Fibonacci series in Python.

4. Write a program to perform the factorial of number?

5. Write a program to compute the number of factorial number between a given range of values?

6. Write a program in Python to check if a number is prime.

7. Write a program in Python to check if a sequence is a Palindrome.

8. Write a one-liner that will count the number of capital letters in a file. Your code should work

even if the file is too big to fit in memory.

9. With suitable approach, Write a sorting algorithm for a numerical dataset in Python.

10. Explain how the python support the dual indexing approach?

11. How does break, continue and pass work in the segment of the Python code?

12. What is the meaning of the segment mentioned as [::-1} do?

13. How can you randomize the items of a list in place in Python? Is it possible in Python? 

14. What are python iterators? Discuss with suitable code?

15. How can you generate random numbers in Python?

16. What is the difference between range & xrange in python?

17. How do you write comments lines in python while writing the program?

18. What is the usage of help() and dir() function in Python?

19. Whenever Python exits, why isn’t all the memory de-allocated?

20. What is a dictionary in Python?

21. How can the ternary operators be used in python?

22. What does this mean: *args, **kwargs? And why would we use it?

23. What is the purpose of the function len()? Explain with example?

24. Explain split(), sub(), subn() methods of “re” module in Python.

Python Libraries Interview Questions:

1. What is pickling and unpickling process in Python? Which library is being used for this process?

2. What are the generators in python? Discuss with suitable example?

3. For a given code in python, How will you capitalize the first letter of string?

4. How will you convert a string to all lowercase using the inbuilt code in python?

5. How to comment multiple lines in python?

6.What are docstrings in Python? Discuss with suitable example?

7. What is the purpose of is, not and in operators? Discuss with suitable example?

8. With suitable approach explain how Multithreading can be achieved in Python?

9. What is the process of compilation and linking in python?

10. What are Python libraries? Name a few of them.

11. What is split used for?

12. How to import modules in python while doing the program? Explain?

OOPS Interview Questions

1. Explain Inheritance in Python with an example.

2. How are classes created in Python? 

3. What is monkey patching in Python?

4. Does python support multiple inheritance?

5. What is Polymorphism in Python?

6. Define encapsulation in Python?

7. How do you do data abstraction in Python?

8. Does python make use of access specifiers?

7. How to create an empty class in Python? 

8. What does an object() do?

9. Explain what Flask is and its benefits?

10. Is Django better than Flask?

11. Mention the differences between Django, Pyramid and Flask.

12. Discuss Django architecture with suitable approach?

13. Explain in python environment how can set up the Database in Django?

14. Give an example how to write a VIEW in Django? Discuss?

15. Mention what the Django templates consist of.

16. Explain the use of session in Django framework?

17.  List out the inheritance styles in Django with suitable approach?

Web Scraping Based Interview Questions on Python:

1. How To Save An Image Locally Using Python Whose URL Address I Already Know?

2. How can you Get the Google cache age of any URL or web page?

3. You are required to scrap data from IMDb top 250 movies page. It should only have fields

movie name, year, and rating.

Data Analysis Based Interview Questions on Python:

1. What is map function in Python?

2. Is python numpy better than lists?

3. How to get indices of N maximum values in a NumPy array?

4.  How do you calculate percentiles with Python/ NumPy?

5. What is the difference between NumPy and SciPy?

6. How do you make 3D plots/visualizations using NumPy/SciPy?

Multiple Choice Questions (MCQ)

1. Which of the following statements create a dictionary? (Multiple Correct Answers Possible)

d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) d = (40:”john”, 45:”50”)

2. Which one of these is floor division?

  1. /
    b) //
    c) %
    d) None of the mentioned

3. What is the maximum possible length of an identifier?
a) 31 characters
b) 63 characters
c) 79 characters
d) None of the above

4. Why are local variable names beginning with an underscore discouraged?

  1. they are used to indicate a private variables of a class
    b) they confuse the interpreter
    c) they are used to indicate global variables
    d) they slow down execution

5. Which of the following is an invalid statement?
a) abc = 1,000,000
b) a b c = 1000 2000 3000

c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000

6. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?
a) Error
b) None
c) 25
d) 2

7. To open a file c:scores.txt for writing, we use
a)outfile = open(“c:scores.txt”, “r”)
b) outfile = open(“c:scores.txt”, “w”)
c) outfile = open(file = “c:scores.txt”, “r”)
d) outfile = open(file = “c:scores.txt”, “o”)

8. When will the else part of try-except-else be executed?

a) always
b) when an exception occurs
c) when no exception occurs
d) when an exception occurs into except block

Scope @ NareshIT:

  1. At NareshIT’s Python application Development program you will be able to get the extensive hands-on training in front-end, middleware, and back-end technology.

  2. It skilled you along with phase-end and capstone projects based on real business scenarios.

  3. Here you learn the concepts from leading industry experts with content structured to ensure industrial relevance.

  4. An end-to-end application with exciting features

  5. Earn an industry-recognized course completion certificate.