Python Advanced Topics

1. write some python which will compatible with all versions of python check with tuple unpacking

2. write a program which will take user input and print all prime numbers in for given range

Builtin Types:

1. globals , locals , eval

2. compile

3. exec

4. eval

5. single

6. scope & Namespace global , local , nonlocal

7. what are the dunder methods

binary search

8. time complexity vs space complexity

Differences :

1. Diff between zip , izip , izip_longest

2. Diff between tuple vs list methods

3. diff between dict vs tuple

4. diff between list vs tuple

5. str vs repr

6. getattr vs getattribute

7. diff between generator iterator , iterables , containers etc

8. diff between _ vs __ starting if we put before variable

Single Underscore

Names, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself.

To quote PEP-8:

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

Double Underscore (Name Mangling)

From the Python docs:

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

And a warning from the same page:

Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private.

Example

```

>>> class MyClass():

... def __init__(self):

... self.__superprivate = "Hello"

... self._semiprivate = ", world!"

...

>>> mc = MyClass()

>>> print mc.__superprivate

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AttributeError: myClass instance has no attribute '__superprivate'

>>> print mc._semiprivate

, world!

>>> print mc.__dict__

{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}

```

Concepts:

1. mutable vs immutable

2. shallow copy vs deep copy

3. iterator , generator , decorator

4. packing vs unpacking

5. list compresion , dict compreshion

6. Exception hadling

7. python descriptors

8. lamda

9. function arguments (*args, **kwargs)

10. module

11. package

12. map filter reduce

flow control :

1. for with else

2. while with else

3. ternary operator

Modules:

1. os module(list , walk , path , join , split , splitext) , request module(get, set , post delete , patch, binary data ) , subprocess() (checkoutput, Popen, child process),

2. json marsling , unmarshlling , which module , diff between dump vs dumps , load vs loads

# Python program explaining

# where() function

​ ​

import ​numpy as np

​ ​

# a is an array of integers.

a = ​np.array([[1, 2, 3], [4, 5, 6]])

​ ​

print(a)

​ ​

print ​('Indices of elements <4')

​ ​

b = ​np.where(a<4)

print(b)

​ ​

print("Elements which are <4")

print(a[b])

Marshaling is the process of converting a programming language’s data type object to a format like XML, JSON etc., With debates aside, marshalling is sometimes referred to as serialization

Unmarshaling is the process of converting a format like XML, JSON etc., to a data type object of the target programming language. With debates aside, unmarshalling is sometimes referred to as deserialization

3. file io read write with chunk or line by line or whole file in one shot etc

4. oops inheritance , composition , aggregation , association multiple inheritance

5. datetime

6. arg parse

7. multithreading

8. multiprocessing

9. critical section

10. semaphore

11. deadlock

12. starvation etc

Advanced :

1. dynamic creation of classes without using class keyword

2. call function dynamically

3. add function dynamically

4. write your own iterator

5. write your own decorator

6. write your own generator(ways to write , generator function , generator expression diff)

Operator:

Datatypes:

Number (int, decimal , float , comples , binary , octal, hexdecimall)

list (slicing)

dict

set

tuple

nametuple

frozenset

string (formatting )

Syntax: {[index]:[width][.precision][type]}

The type can be used with format codes:

* ‘d’ for integers

* ‘f’ for floating-point numbers

* ‘b’ for binary numbers

* ‘o’ for octal numbers

* ‘x’ for octal hexadecimal numbers

* ‘s’ for string

* ‘e’ for floating-point in an exponent format

Example:

* Python

print('The valueof pi is: %1.5f' %3.141592)

# vs.

print('The valueof pi is: {0:1.5f}'.format(3.141592))

)

regex to find pattern count

any

Check if a String contains all strings from a List

In Python all(iterable) function accepts an iterable as an argument and returns if all elements in the iterable are True. We can use List comprehension and all() to check if all elements from a list exists in the given string i.e.

```

mainStr = "This is a sample String with sample message."

listOfstrs = ['sample', 'String', 'with']

# Check if all strings from the list exists in given string

result = all(([True if subStr in mainStr else False for subStr in listOfstrs]))

if result:

print('All strings from list Found in main String ')

```

Last updated