Python Data Types: Operations & Methods Cheat Sheet
String (str) 📘
════════════════
Methods:
lower(), upper(), strip(), replace(), split(), find(), count(),
startswith(), endswith(), join(), title(), splitlines(), lstrip(),
rstrip(), isalpha(), isdigit(), isalnum(), partition(), format(), encode()
Operations:
Concatenation: 'Hi' + '!' → 'Hi!'
Repetition: '-' * 10 → '----------'
Length: len('Python') → 6
Membership: 'a' in 'apple' → True
Slicing: text[2:5] → substring
Formatting:
f"Value: {x}" (f-strings)
"{}".format(var) (format method)
Integer (int) 🔢
════════════════
Methods:
bit_length(), to_bytes(), from_bytes(), as_integer_ratio()
Operations:
Arithmetic:
7 + 3 → 10 (Addition)
7 - 3 → 4 (Subtraction)
7 * 3 → 21 (Multiplication)
7 // 3 → 2 (Floor division)
7 % 3 → 1 (Modulus)
7 ** 3 → 343 (Exponentiation)
Bitwise:
5 & 3 → 1 (AND)
5 | 3 → 7 (OR)
5 ^ 3 → 6 (XOR)
5 << 1 → 10 (Left shift)
5 >> 1 → 2 (Right shift)
~5 → -6 (NOT)
Float 🔢
════════
Methods:
is_integer(), hex(), fromhex(), as_integer_ratio()
Operations:
2.5 + 1.5 → 4.0
5.0 / 2 → 2.5
round(3.14159, 2) → 3.14
float.is_integer(5.0) → True
Comparisons: 3.0 > 2.9 → True
List 📜
════════
Methods:
append(), extend(), insert(), remove(), pop(), clear(), sort(),
reverse(), copy(), count(), index()
Operations:
Concatenation: [1,2] + [3] → [1,2,3]
Repetition: [0] * 3 → [0,0,0]
Length: len([1,2,3]) → 3
Membership: 3 in [1,2,3] → True
Slicing: lst[1:3] → sublist
Sum: sum([1,2,3]) → 6
Min/Max: min([1,2,3]) → 1, max([1,2,3]) → 3
List Comprehension: [x*2 for x in lst]
Unpacking: a, b, c = [1,2,3]
📦
Set
═══════
Methods:
add(), remove(), discard(), pop(), clear(), union(), intersection(),
difference(), symmetric_difference(), update(), isdisjoint(), issubset(),
issuperset()
Operations:
Union: {1,2} | {2,3} → {1,2,3}
Intersection: {1,2} & {2,3} → {2}
Difference: {1,2} - {2,3} → {1}
Symmetric Difference: {1,2} ^ {2,3} → {1,3}
Membership: 3 in {1,2,3} → True
Subset: {1} <= {1,2} → True
Set Comprehension: {x**2 for x in s}
🧱
Tuple
═════════
Methods:
count(), index()
Operations:
Concatenation: (1,2) + (3,) → (1,2,3)
Repetition: ('Hi',) * 2 → ('Hi','Hi')
Length: len((1,2,3)) → 3
Membership: 2 in (1,2,3) → True
Slicing: tup[1:] → (2,3)
Unpacking: x, y, z = (10,20,30)
Sum: sum((1,2,3)) → 6
🔑
Dictionary (dict)
════════════════════
Methods:
get(), keys(), values(), items(), pop(), popitem(), clear(),
copy(), update(), setdefault(), fromkeys()
Operations:
Value Access: d['key'] → value
Key Check: 'key' in d → True
Length: len(d) → number of keys
Key Deletion: del d['key']
Merge (Python 3.9+): d1 | d2
Dictionary Comprehension: {k:v*2 for k,v in d.items()}
Safe Access: d.get('missing', default) → default value
Key Notes:
══════════
• Immutability: Strings, tuples, integers, floats are immutable
• Order Preservation: Lists, tuples, and dicts (Python 3.7+) maintain insertion
order
• Comprehensions: Available for lists, sets, and dictionaries
• Unpacking: Works with lists, tuples, and dictionaries (for keys)
Here’s a **formatted and enhanced** version of your notes for better readability
and structure, while preserving all original content and adding clarity:
---
# 🐍 Python Loop and File Iteration — *Behind the Scenes*
---
## 1. 🔁 How `for` Loops Work Internally
### ✅ Example Code:
```python
for i in [1, 2, 3]:
print(i)
```
### ⚙️ What Happens Behind the Scenes:
```python
items = [1, 2, 3]
it = iter(items)
while True:
try:
i = next(it)
print(i)
except StopIteration:
break
```
### 🧠 Key Concepts:
* `iter()` converts an iterable (e.g., list) to an iterator.
* `next()` fetches the next item from the iterator.
* The `for` loop implicitly uses `iter()` and `next()` under the hood.
---
## 2. 📂 How File Iteration Works
### ✅ Example Code:
```python
with open('file.txt') as f:
for line in f:
print(line)
```
### ⚙️ What Happens Behind the Scenes:
```python
f = open('file.txt')
it = iter(f)
while True:
try:
line = next(it)
print(line)
except StopIteration:
break
```
### 🧠 Key Concepts:
* File objects are their own iterators.
* `next()` reads the next line from the file.
* Iteration stops when `StopIteration` is raised (EOF).
---
## 3. 🔄 Built-in Functions & Methods That Produce Iterators
These functions return **lazy iterators** and must be iterated over using `next()`
or a loop.
### ⚙️ General Iterator-Producing Functions:
* `iter()`
* `enumerate()`
* `zip()`
* `map()`
* `filter()`
* `reversed()`
* `range()`
### 📁 File Iterators:
* `open().readline()`
* `open().readlines()`
### 🧾 Dictionary Views:
* `dict.items()`
* `dict.keys()`
* `dict.values()`
### ⚙️ Core Iterator Protocol:
* `__iter__()`
* `__next__()`
* `next()`
### ⚡ Generator-based Iterators:
* Generator functions using `yield`
* Generator expressions: `(x for x in iterable)`
---
## 4. 🔤 Common Data Types, Their Methods, and Operations
### A. `str` (String)
#### Methods:
`capitalize`, `casefold`, `center`, `count`, `encode`, `endswith`, `expandtabs`,
`find`, `format`, `format_map`,
`index`, `isalpha`, `isdigit`, `islower`, `isspace`, `istitle`, `join`, `lower`,
`lstrip`, `replace`,
`rfind`, `rindex`, `rjust`, `split`, `strip`, `title`, `upper`, `zfill`...
#### ➕ Operations:
Concatenation (`+`), Repetition (`*`), Indexing (`[]`), Slicing (`[:]`), `in`, `not
in`
---
### B. `int`
#### Methods:
`bit_length()`, `to_bytes()`, `from_bytes()`, `conjugate()`, `as_integer_ratio()`,
`is_integer()`
#### ➕ Operations:
`+`, `-`, `*`, `/`, `//`, `%`, `**`, bitwise ops (`&`, `|`, `^`, `~`, `<<`, `>>`),
comparisons
---
### C. `float`
#### Methods:
`is_integer()`, `as_integer_ratio()`, `hex()`, `fromhex()`
#### ➕ Operations:
Same as for `int`
---
### D. `complex`
#### Methods:
`conjugate()`
#### ➕ Operations:
`+`, `-`, `*`, `/`, `**`, comparisons (`==`, `!=`)
---
### E. `list`
#### Methods:
`append`, `extend`, `insert`, `remove`, `pop`, `clear`, `index`, `count`, `sort`,
`reverse`, `copy`
#### ➕ Operations:
Concatenation (`+`), Repetition (`*`), Indexing (`[]`), Slicing (`[:]`), `in`, `not
in`, `len()`, `del`, iteration
---
### F. `tuple`
#### Methods:
`count`, `index`
#### ➕ Operations:
Same as list (but immutable)
---
### G. `set` / `frozenset`
#### Methods:
`add`, `clear`, `copy`, `difference`, `intersection`, `isdisjoint`, `issubset`,
`union`, `update`, etc.
#### ➕ Operations:
`|`, `&`, `-`, `^`, comparisons, `in`, `not in`, iteration
---
### H. `dict`
#### Methods:
`clear`, `copy`, `fromkeys`, `get`, `items`, `keys`, `pop`, `update`, `values`,
etc.
#### ➕ Operations:
Indexing (`[]`), `in`, `not in`, `del`, `len()`, iteration
---
## 5. 🔧 Built-in Functions That Work with Iterators or Common Types
| Function | Returns Iterator | Works With
|
| ---------------------------------- | ------------------- |
------------------------------------- |
| `iter()` | ✅ Yes | `str`, `list`,
`tuple`, `set`, `dict` |
| `reversed()` | ✅ Yes | `str`, `list`, `tuple`
|
| `enumerate()` | ✅ Yes | All iterables
|
| `zip()` | ✅ Yes | All iterables
|
| `map()` | ✅ Yes | All iterables
|
| `filter()` | ✅ Yes | All iterables
|
| `range()` | ✅ Yes | `int`
|
| `sorted()` | ❌ No (returns list) | All iterables
|
| `all()` / `any()` | ❌ No (returns bool) | All iterables
|
| `next()` | ❌ No | Works on iterators
|
| `sum()` / `min()` / `max()` | ❌ No | Iterable of
numbers/comparables |
| `len()` | ❌ No | `str`, `list`,
`tuple`, `set`, `dict` |
| `type()` / `id()` / `isinstance()` | ❌ No | All data types
|
---
📌 **Other Notes:**
* All **iterables** support: `iter()`, `next()`, `for` loops, `list()`, `tuple()`,
`sorted()`, `sum()`, etc.
* **Iterators** can be converted to lists using `list()`, `tuple()`, or `set()`.
---
Here is a **clean, structured, and enhanced version** of your entire content with
clear headings, bullet points, code formatting, and proper grouping for
readability. This can be easily used as a study guide or documentation.
---
# 📁 Python File Handling — Methods and Operations
---
## 1. 🔧 Core File Handling Methods
| Method | Description |
| ---------------------- | ----------------------------------------------- |
| `open(filename, mode)` | Opens a file and returns a file object |
| `close()` | Closes the opened file |
| `read(size)` | Reads up to `size` bytes (all if not specified) |
| `readline()` | Reads one line at a time |
| `readlines()` | Reads all lines and returns them as a list |
| `write(string)` | Writes a string to the file |
| `writelines(list)` | Writes a list of strings to the file |
| `seek(offset, whence)` | Moves the cursor to a specific file position |
| `tell()` | Returns the current file cursor position |
| `flush()` | Flushes internal buffer to disk |
| `truncate(size)` | Truncates the file to a specific size |
---
## 2. File Modes (Used with `open()`)
| Mode | Description |
| ----- | ------------------------------------------ |
| `'r'` | Read (default) — File must exist |
| `'w'` | Write — Creates or truncates existing file |
| `'a'` | Append — Adds content at the end |
| `'x'` | Exclusive creation — Fails if file exists |
| `'b'` | Binary mode (e.g. `'rb'`, `'wb'`) |
| `'t'` | Text mode (default) |
| `'+'` | Read and write (e.g. `'r+'`, `'w+'`) |
---
## 3. 🧰 Useful File & OS Functions
```python
with open(filename, mode) as file:
# auto-closes file
```
| Function | Description |
| -------------------------- | --------------------------------- |
| `os.path.exists(filename)` | Checks if a file exists |
| `os.remove(filename)` | Deletes a file |
| `os.rename(src, dst)` | Renames a file |
| `os.listdir(path)` | Lists files/directories in a path |
| `os.path.getsize(file)` | Gets file size in bytes |
| `shutil.copy(src, dst)` | Copies a file |
| `shutil.move(src, dst)` | Moves a file |
| `os.makedirs(path)` | Creates nested directories |
---
## 4. 📄 Common File Handling Patterns
### ✅ Reading:
```python
with open('file.txt', 'r') as f:
content = f.read()
```
### ✍️ Writing:
```python
with open('file.txt', 'w') as f:
f.write('Hello')
```
### ➕ Appending:
```python
with open('file.txt', 'a') as f:
f.write('\nNew line')
```
### Binary:
```python
with open('image.jpg', 'rb') as f:
data = f.read()
```
---
## 5. Modern File Handling with `pathlib`
```python
from pathlib import Path
file = Path('example.txt')
file.write_text('Hello')
content = file.read_text()
exists = file.exists()
file.unlink() # Deletes file
```
---
## 6. 🔄 Understanding `iter()` and `next()`
* `iter(obj)` → Converts an iterable to an iterator.
* `next(it)` → Retrieves the next item from an iterator.
* Raises `StopIteration` when exhausted.
---
## 7. 🔎 `iter()` and `next()` Examples
```python
# String
s = 'hello'
it = iter(s)
print(next(it)) # 'h'
# List
l = [1, 2, 3]
it = iter(l)
print(next(it)) # 1
# Dictionary keys
d = {'a': 1}
it = iter(d)
print(next(it)) # 'a'
# Dictionary items
it = iter(d.items())
print(next(it)) # ('a', 1)
# File
with open('file.txt') as f:
print(next(f)) # First line
```
---
## 8. ⚙️ Behind the Scenes: `iter()` + `next()` in Loops
```python
# for item in [1, 2, 3]:
# print(item)
# Internally:
it = iter([1, 2, 3])
try:
while True:
item = next(it)
print(item)
except StopIteration:
pass
```
---
# 🧠 Python Function Parameters & Scope
## 🧩 Parameter Priority (Highest to Lowest):
1. **Positional-only** → `def func(a, /)`
2. **Positional or Keyword** → `def func(a)`
3. **Default Values** → `def func(a=5)`
4. **Var-positional** (`*args`) → `def func(*args)`
5. **Keyword-only** → `def func(*, b)`
6. **Var-keyword** (`**kwargs`) → `def func(**kwargs)`
---
## 🧬 Variable Scope (LEGB Rule):
1. **Local (L)** – Inside the current function.
2. **Enclosing (E)** – Enclosing function scopes.
3. **Global (G)** – Module-level variables.
4. **Built-in (B)** – Python built-ins (e.g., `len`, `range`).
---
# 🧭 Comprehensive Study Plan: Become a Professional Python Developer
---
## 📅 Week 1: Python Basics
**Topics:**
* Syntax, Variables, Data Types, Operators, Control Flow, Loops
**Practice Questions:**
* Check number sign
* Factorial
* Fibonacci series
* Palindrome check
**Mini Project:** Simple calculator
---
## 📅 Week 2: Functions and Modules
**Topics:**
* Defining Functions, Lambda, Modules
**Project:** Create a custom math module
---
## 📅 Week 3: File Handling
**Topics:**
* Text & CSV file handling
**Project:** Analyze student grades from a CSV
---
## 📅 Week 4: Object-Oriented Programming (OOP)
**Topics:**
* Classes, Inheritance, Polymorphism, Encapsulation
**Project:** Library Management System
---
## 📅 Week 5: Exception Handling
**Topics:**
* Try/Except, Raising, Custom Exceptions
**Project:** Input validator with custom exceptions
---
## 📅 Week 6: Python Standard Library
**Topics:**
* `os`, `sys`, `math`, `datetime`
**Project:** File organizer by type
---
## 📅 Week 7: Web Development with Flask
**Topics:**
* Flask basics, Routing, Templates
**Project:** Personal Blog
---
## 📅 Week 8: Web Development with Django
**Topics:**
* Django setup, Models, Views, Forms
**Project:** E-commerce website
---
## 📅 Week 9: Data Science with Python
**Topics:**
* NumPy, Pandas, Matplotlib
**Project:** Dataset analysis with visualizations
---
## 📅 Week 10: Advanced Python Concepts
**Topics:**
* Decorators, Generators, Context Managers
**Project:** Web scraper using advanced features
---
## 📅 Week 11: Testing and Debugging
**Topics:**
* `unittest`, Debugging tools
**Project:** Create test suite for a small app
---
## 📅 Week 12: Deployment & Git
**Topics:**
* Git, GitHub, Heroku Deployment
**Project:** Deploy Flask or Django app to Heroku
---
## 🏁 Final Projects (Choose One)
* Web Scraper
* Chatbot
* ML Model Deployment
* REST API with Frontend
* Python Game (e.g., with Pygame)
---
### 🚀 Conclusion
By following this structured plan, you'll build a solid Python foundation and gain
real-world development experience. Stay consistent, build projects, and practice
problem-solving to become a proficient Python developer.