Edit Content
Click on the Edit Content button to edit/add the content.
Edit Content
Click on the Edit Content button to edit/add the content.
Edit Content

Python is popular due to its simple syntax, readability, and versatility. It's an interpreted, cross-platform language with a rich standard library and extensive third-party frameworks for web development, data analysis, and AI. It supports multiple paradigms (OOP, procedural, functional), features dynamic typing, and integrates well with other technologies. Its large community ensures abundant resources, making it ideal for beginners and experts alike.

 

Lists: Mutable, use [], suitable for modifiable data.

      Tuples: Immutable, use (), ideal for fixed data.

Example:

  • List: shopping_list = ["apples", "bananas"] (can add/remove items).
  • Tuple: coordinates = (10.5, 20.3) (fixed values).

The __init__ method in Python is a special constructor method used to initialize an object's attributes when an instance of a class is created. Unlike other methods, it is automatically called and doesn't return any value explicitly (it always returns None).

def count_vowels(s):

return sum(1 for char in s.lower() if char in 'aeiou')

# Example usage

print(count_vowels("Hello World"))  # Output: 3

Python's data types include int, float, str, list, tuple, dict, set, bool, and None. Examples: 5, 3.14, "hello", [1, 2], (1, 2), {'key': 'value'}, {1, 2}, True, and None.

A shallow copy creates a new object but copies references to the original elements, so changes to mutable objects affect both copies. A deep copy creates a completely independent copy, including copying nested objects, so changes don't affect the original.

Python handles memory management through automatic garbage collection and reference counting. When objects are no longer referenced, they are deallocated, and the memory is freed, typically using the garbage collector to handle cycles and unreferenced objects.

Python's built-in data structures are:

  1. List: Ordered, mutable collection (e.g., [1, 2, 3])
  2. Tuple: Ordered, immutable collection (e.g., (1, 2, 3))
  3. Dictionary: Key-value pairs (e.g., {'name': 'Alice', 'age': 25})
  4. Set: Unordered collection of unique elements (e.g., {1, 2, 3})

In Python, == checks if the values of two objects are equal, while is checks if two objects refer to the same memory location (i.e., whether they are the same object).

Decorators in Python are functions that modify the behavior of other functions or methods. They are used to add functionality to existing code without changing the original function, typically applied using the @decorator_name syntax.

Python's comprehensions provide a concise way to create lists, sets, or dictionaries. Examples:

  • List comprehension: [x**2 for x in range(5)] → [0, 1, 4, 9, 16]
  • Set comprehension: {x**2 for x in range(5)} → {0, 1, 4, 9, 16}

Dictionary comprehension: {x: x**2 for x in range(5)} → {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Python's garbage collection uses reference counting to track the number of references to an object. When an object's reference count reaches zero, it is automatically deallocated. Additionally, Python uses a cyclic garbage collector to detect and clean up circular references that reference counting alone can't handle.

staticmethod: A method that doesn't take self or cls as its first argument and is not bound to an instance or class. It behaves like a regular function but belongs to the class.

classmethod: A method that takes cls as its first argument, allowing it to access or modify the class state, and is bound to the class, not an instance.

 

Exception handling in Python is implemented using try, except, else, and finally blocks. The try block contains code that may raise an exception, the except block handles the exception, the else block runs if no exception occurs, and the finally block executes regardless of an exception.

A Python generator is a function that uses yield to produce a sequence of values lazily, one at a time, instead of returning the entire sequence at once. Unlike a list, a generator does not store all values in memory, making it more memory-efficient for large datasets.

*args allows a function to accept any number of positional arguments as a tuple.

 **kwargs allows a function to accept any number of keyword arguments as a dictionary.

 

Python's lambda functions are anonymous, small functions defined using the lambda keyword. They can have any number of arguments but only one expression.

Example: python

Copy code

add = lambda x, y: x + y

print(add(2, 3))  # Output: 5

map(): Applies a function to all items in an iterable and returns a map object (e.g., [f(x) for x in iterable]).

 filter(): Filters elements from an iterable based on a condition function, returning items that evaluate to True.

 reduce(): Performs a cumulative operation on items of an iterable, reducing it to a single value (from the functools module).

copy() creates a shallow copy, copying only the references to objects within the original, not the nested objects.

 deepcopy() creates a deep copy, recursively copying all objects and nested objects, ensuring complete independence from the original.

You can convert a Python string into a datetime object using the strptime() method from the datetime module.

Example:python

Copy code

from datetime import datetime

date_string = "2024-12-06"

date_object = datetime.strptime(date_string, "%Y-%m-%d")

In Python, files are handled using the open() function, which returns a file object. You can read, write, or append to the file with methods like .read(), .write(), and .close(). It's best practice to use the with statement to ensure files are properly closed.

Example:python

Copy code

with open('file.txt', 'r') as file:

content = file.read()

Python's with statement is used for resource management, ensuring that resources like files or network connections are properly acquired and released. It automatically handles setup and cleanup (e.g., closing files) when the block of code is executed, even if an exception occurs.

You can create a virtual environment in Python using the venv module.

Example:

bash

Copy code

python -m venv myenv

To activate:

  • Windows: myenv\Scripts\activate
  • Mac/Linux: source myenv/bin/activate

Deactivate with: deactivate

Iterable: An object that can return an iterator, such as a list, tuple, or string, and supports iteration (e.g., using a for loop).

Iterator: An object that represents a stream of data and can be iterated upon, using __next__() to fetch the next item until exhaustion.

Multithreading: Involves running multiple threads within the same process, sharing memory space. It's useful for I/O-bound tasks but may not be efficient for CPU-bound tasks due to Python's Global Interpreter Lock (GIL).

 Multiprocessing: Involves running multiple processes, each with its own memory space. It's more effective for CPU-bound tasks as it bypasses the GIL and utilizes multiple cores.

Inheritance is implemented by defining a class that inherits from another class:

python

Copy code

class Animal:

def speak(self):

     print("Animal speaks")

 

class Dog(Animal):

def speak(self):

     print("Dog barks"

 

python

Copy code

def reverse_string(s):

if len(s) == 0:

     return s

else:

     return reverse_string(s[1:]) + s[0]

 

  • Simple and readable syntax
  • Dynamically typed
  • Extensive standard library
  • High-level, interpreted, and cross-platform

python

Copy code

def is_prime(n):

if n < 2:

     return False

for i in range(2, int(n**0.5) + 1):

     if n % i == 0:

         return False

return True

Python determines variable types at runtime, allowing variables to change types dynamically.

python

Copy code

def factorial(n):

if n == 0:

     return 1

return n * factorial(n - 1)

Mutable: Can be changed after creation (e.g., lists, dictionaries).

Immutable: Cannot be changed after creation (e.g., strings, tuples).

Use libraries like pandas with methods like fillna(), dropna(), or interpolation to handle missing values.

Python's exceptions are organized in a hierarchy, with BaseException as the root. Common exceptions include Exception, ValueError, and IndexError.
Example:

python

Copy code

try:

x = int("hello")

except ValueError:

    print("Invalid number!")

Use the update() method or dictionary unpacking (**):

python

Copy code

dict1 = {'a': 1}

dict2 = {'b': 2}

dict1.update(dict2)  # Merges dict2 into dict1

# or

merged_dict = {**dict1, **dict2}

A Python module is a file containing Python code that defines functions, classes, or variables. Create a module by saving a .py file, and import it using import module_name.

python

Copy code

with open('file.txt', 'r') as file:

line_count = sum(1 for line in file)

print(line_count)

 

Python's dictionary is implemented using a hash table, providing average O(1) time complexity for lookups, insertions, and deletions.

yield turns a function into a generator, allowing it to return values one at a time without storing them in memory, making it memory efficient for large datasets.

python

Copy code

def find_duplicates(lst):

return [item for item in set(lst) if lst.count(item) > 1]