Essential Python Programming Concepts and Examples

Mutable vs Immutable Data Types

  • Mutable: Value can be changed after creation. Examples: list, dict, set.
  • Immutable: Value cannot be changed after creation. Examples: int, float, string, tuple.
  • Mutable objects can be modified in place; immutable objects create a new object on modification.

Break vs Continue Statements

  • break: Terminates the loop immediately and control moves to the statement after the loop.
  • continue: Skips the current iteration and moves to the next iteration of the loop.
for i in range(5):
    if i == 3: break
    if i == 2: continue
    print(i) # prints 0, 1

Tuple to List Conversion

Code:

x = (1, 2, 3)
y = list(x)
y.append(4)
print(y)

Output: [1, 2, 3, 4] — tuple is converted to list, then 4 is appended.

The Pass Statement

  • pass is a null statement; it does nothing when executed.
  • Used as a placeholder where code is syntactically required but no action is needed (e.g., empty function/class/loop body).

List Methods: Append vs Extend

  • append(x): Adds x as a single element at the end of the list.
  • extend(iter): Adds each element of the iterable to the end of the list.

The __init__ Method

  • __init__() is the constructor of a class — automatically called when an object is created.
  • Used to initialize the object’s attributes (instance variables).
  • First parameter is always self (refers to the new object).

NumPy Identity Matrix

numpy.eye(n) creates an n x n identity matrix (1s on diagonal, 0s elsewhere).

Dynamic Typing in Python

Dynamic typing means the type of a variable is decided at runtime, not at compile time. The same variable can hold different data types during execution.

Advantages:

  • No need to declare variable type — code is shorter and faster to write.
  • More flexible; same function can handle different data types.

Disadvantages:

  • Type-related errors are caught only at runtime.
  • Slower execution compared to statically typed languages.
  • Code may become harder to debug in large projects.

Removing Duplicates from a List

Method 1: Using set (does not preserve order)

def remove_duplicates(lst):
    return list(set(lst))

Method 2: Preserving order

def remove_duplicates(lst):
    result = []
    for item in lst:
        if item not in result:
            result.append(item)
    return result

Python Functions

A function is a reusable block of code that performs a specific task.

  • Defined using the def keyword.
  • Can take parameters (input) and return a value (output).
  • Helps in code reusability and modularity.

File Processing: Lines, Words, and Characters

def count_file(filename):
    lines = words = chars = 0
    with open(filename, 'r') as f:
        for line in f:
            lines += 1
            words += len(line.split())
            chars += len(line)
    return lines, words, chars

Data Visualization with Matplotlib

matplotlib is a library used for creating 2D plots. The pyplot module provides MATLAB-like plotting functions.

Loops and the Else Clause

  • for loop: Used to iterate over a sequence.
  • while loop: Repeats as long as a condition is true.
  • else with loop: The else block runs if the loop completes normally (without break).

Finding the LCM of Two Numbers

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def lcm(a, b):
    return (a * b) // gcd(a, b)

String Operations

  • Common letters: Use set(s1) & set(s2) for intersection.
  • Vowel counting: Iterate through the string and check against "aeiouAEIOU".

Sets, Lists, and Dictionaries

  • Set: Unordered collection of unique elements.
  • List: Ordered collection, accessed by index.
  • Dictionary: Unordered key-value pairs, accessed by key.

Lambda Functions and List Comprehensions

Lambda: Anonymous one-line function defined using the lambda keyword.

List Comprehension: Compact way to create lists: [expression for item in iterable].

File Opening Modes

  • ‘r’: Read mode.
  • ‘w’: Write mode (overwrites).
  • ‘a’: Append mode.
  • ‘b’: Binary mode.

Generators vs Iterators

  • Generator: A function that returns an iterator using the yield keyword; memory-efficient.
  • Iterator: Object that implements __iter__() and __next__().

Random Numbers with NumPy

Use numpy.random.randint(low, high, size) to generate random integers.

Pandas DataFrame

A 2D, size-mutable, tabular data structure in pandas. It has labeled rows (index) and columns, similar to an Excel sheet.