Python Learning
5.76K subscribers
568 photos
2 videos
106 files
129 links
Python learning resources

Beginner to advanced Python guides, cheatsheets, books and projects.

For data science, backend and automation.
Join πŸ‘‰ https://rebrand.ly/bigdatachannels

DMCA: @disclosure_bds
Contact: @mldatascientist
Download Telegram
⚑️ append() vs extend()

These two methods look similar, but they do completely different things.
numbers = [1, 2, 3]

numbers.append([4, 5])

print(numbers)

Output:
[1, 2, 3, [4, 5]]


Now compare it with:
numbers = [1, 2, 3]

numbers.extend([4, 5])

print(numbers)

Output:
[1, 2, 3, 4, 5]


πŸ‘‰ append() adds one object.
πŸ‘‰ extend() adds every element.

This small difference causes countless beginner bugs.
❀5
πŸ“š 10 Python Modules You Probably Didn't Know Existed

1. textwrap - Format long blocks of text.
2. difflib - Compare files or strings.
3. fractions - Work with exact fractions.
4. decimal - High precision decimal arithmetic.
5. calendar - Generate calendars programmatically.
6. uuid - Generate unique IDs.
7. secrets - Create cryptographically secure tokens.
8. pprint - Print nested data structures beautifully.
9. platform - Detect operating system information.
10. getpass - Securely read passwords from the terminal.
❀5πŸ‘1
πŸ“– Reading Python Error Messages

Suppose you see this.
TypeError: can only concatenate str (not "int") to str

Instead of panicking, read it from left to right.

TypeError β†’ The operation uses the wrong data type.
str β†’ Python found a string.
int β†’ It also found an integer.

πŸ‘‰ You're trying to combine two incompatible types.
❀3
⚑️ Why Is This Loop So Slow?

Imagine you're checking whether thousands of usernames exist.
for username in usernames:
if username in banned_users:
...


If banned_users is a list, Python checks one element at a time.
Alice?

Bob?

Charlie?

David?

...

For every lookup.

Now imagine banned_users is a set. Python doesn't search one by one. It uses a hash table to jump directly to where the value should be.

That's why changing this:
banned_users = [...]

into this:
banned_users = {...}

can dramatically speed up membership checks without changing the rest of your code.
❀3
Python Operators Explained
❀5
🐍 Python Type Checking

πŸ”Ή What is Type Checking?
Type checking is the process of checking the data type of a value or variable. Python provides several ways to do this.

age = 17
name = "Ted"
skills = ["Python", "AI", "Data Science"]

print(type(age)) # <class 'int'>
print(type(name)) # <class 'str'>
print(type(skills)) # <class 'list'>

πŸ”Ή Using isinstance()
isinstance() is often more useful when you want to check whether a value belongs to a particular type.
age = 17

if isinstance(age, int):
print("Age is an integer")


πŸ”Ή Type Hints
Python also supports type hints, which make your code easier to understand and allow tools such as IDEs and static type checkers to detect potential problems.
def calculate_total(price: float, quantity: int) -> float:
return price * quantity


Here:
price: float β†’ expected to be a decimal number
quantity: int β†’ expected to be an integer
-> float β†’ expected return type


πŸ“Œ Key takeaway:
Python is dynamically typed, but that doesn't mean you should ignore types. Using type(), isinstance(), and type hints can make your Python code more reliable and easier to maintain.
❀3
🧠 dict.get() in Python

Suppose you have this dictionary.
user = {
"name": "Alice",
"age": 24
}


Now you try to access a key that doesn't exist.
print(user["email"])

πŸ”»Python raises:
KeyError: 'email'


Sometimes that's exactly what you want. A missing key should crash the program.

But often, a missing value is perfectly normal.
Instead of checking manually:
if "email" in user:
email = user["email"]
else:
email = None

🟒 Python provides:
email = user.get("email")


If the key exists, you get its value.
If it doesn't, you get None instead of a crash.

You can even choose a default value.
email = user.get("email", "Not provided")


πŸ‘‰ get()
isn't shorter just for the sake of being shorter. It expresses the idea that a missing key is expected.
πŸ‘2❀1
17 Python Functions Every Beginner Must Know ✍️
❀3πŸ‘1
πŸš€ 50 Python Project Ideas

Whether you're a beginner or an experienced Python developer, building projects is the fastest way to improve your skills. Here's a curated list of 50 Python project ideas!

🟒 Beginner
1. Calculator
2. To-Do List App
3. Number Guessing Game
4. Password Generator
5. Dice Rolling Simulator
6. Rock Paper Scissors Game
7. Countdown Timer
8. Unit Converter
9. Digital Clock
10. Contact Book
11. Expense Tracker
12. BMI Calculator
13. QR Code Generator
14. Quiz Application
15. Hangman Game

🟑 Intermediate
16. Weather App (API)
17. Currency Converter
18. URL Shortener
19. File Organizer
20. PDF Merger & Splitter
21. Bulk Image Resizer
22. YouTube Video Downloader
23. Web Scraper
24. Email Automation Tool
25. News Aggregator
26. Markdown to HTML Converter
27. Flashcard Learning App
28. Voice Assistant
29. Chat Application
30. Music Player

πŸ”΄ Advanced
31. AI Chatbot
32. Face Recognition Attendance System
33. Object Detection with YOLO
34. Sentiment Analysis Tool
35. Fake News Detector
36. Stock Price Prediction
37. Recommendation System
38. Resume Screening System
39. AI Image Caption Generator
40. Handwritten Digit Recognition

⚑️ Automation & Dev Tools
41. Website Uptime Monitor
42. Automated Backup Tool
43. File Encryption Tool
44. Network Port Scanner
45. Password Manager
46. Typing Speed Tester
47. Clipboard Manager
48. WiFi Password Viewer (For Your Own Device)
49. API Testing Tool
50. Personal Finance Dashboard

πŸ’‘ Which project are you planning to build next? Let us know in the comments! πŸ‘‡
❀4
Python One-Liners That Could Save You Hours
❀4
🐍 Python’s Secret Memory Saver: __slots__ ⚑️

πŸ‘‰ Most Python tutorials teach you Object-Oriented Programming (OOP) using self.variable = value. But almost none mention what happens under the hood or how it can quietly eat up your RAM.

When you create thousands or millions of object instances, Python’s default behavior wastes a massive amount of memory. Here is how __slots__ fixes that.

β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

πŸ”Ή 1. The Hidden Problem with Default Python Classes

By default, Python stores an object's attributes in a dynamic dictionary called __dict__.

πŸ‘‰ Why this is a problem:

❌ Dictionaries are flexible, but extremely memory-heavy.
❌ Every single instance gets its own dictionary overhead.
❌ If you instantiate 100,000 objects, your application’s RAM usage skyrockets.

β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

πŸ”₯ 2. The Solution: __slots__

__slots__ tells Python:
Do not create a dynamic
__dict__ for this class. Only allow these specific attribute names.



β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

πŸ”Ή 3. Standard Class vs. Slotted Class

❌ Standard Class (Uses Heavy __dict__):

class DataPoint:

def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z


βœ… Optimized Class with __slots__:

class DataPoint:
# Restrict attributes & eliminate __dict__
__slots__ = ("x", "y", "z")

def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z


β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

πŸ“Š 4. The Real-World Impact

By adding that single line of code (__slots__):

βœ”οΈ ~60% to 70% reduction in memory usage across large object lists.
βœ”οΈ Faster attribute access (up to 20% faster speed because Python skips dictionary lookups).

β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

⚠️ 5. The Trade-Off (What You Must Know)

Because __slots__ locks down your object structure:

❌ You cannot dynamically add new attributes at runtime (e.g., point.new_var = 10 will throw an AttributeError).

β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

❔ 6. When Should You Use It?

βœ”οΈ Working with huge datasets or simulation objects in memory.
βœ”οΈ Building high-performance backend microservices.
βœ”οΈ Designing lightweight data structures (like custom Nodes, Vectors, or Points).
❀3
Forwarded from Programming Quiz Channel
Topic: Python

πŸ” Quick look before the question:

def outer():
x = 10
def inner():
nonlocal x
x += 5
return x
return inner

f = outer()
print(f())
print(f())
4 Different Patterns in Python
❀4
Python for Data Science Cheat Sheet.pdf
372.3 KB
Python for Data Science Cheatsheet
πŸ‘1πŸ”₯1
🐍 Python’s Hidden Loop Feature: for...else

πŸ‘‰ Did you know else isn't just for if statements?

Python has a unique feature almost never mentioned in beginner tutorials: you can attach an else block directly to a for or while loop.

πŸ”Ή How It Works

The else block executes ONLY if the loop finishes completely without hitting a break statement.

πŸ”Ή The Difference

❌ Traditional Way (Requires a messy flag variable):

found = False
for user in users:
if user == "Alex":
found = True
break

if not found:
print("User not found!")


βœ… Pythonic Way (Using for...else):

for user in users:
if user == "Alex":
print("User found!")
break
else:
print("User not found!")



πŸ”Ή Why Use It?

βœ”οΈ Eliminates unnecessary boolean flags (like found = True).
βœ”οΈ Cleaner, more readable syntax for search functions.
❀2πŸ‘1
python-cheat-sheet.pdf
155.6 KB
Python CheatSheet
❀2πŸ”₯1
⚑️ Python’s 1-Line Speed Booster: @lru_cache

πŸ‘‰ Did you know you can make slow Python functions run up to 100x faster by adding a single line of code?

Most tutorials skip functools.lru_cache, but it’s one of Python’s best built-in performance hacks.

πŸ”Ή How It Works

It automatically caches (remembers) the results of function calls. If you call the function with the same inputs again, Python skips the heavy computation and returns the saved answer instantly.

πŸ”Ή Code Comparison

❌ Slow (Re-calculates every single call):

def get_user_data(user_id):
# Imagine an expensive database query here
return fetch_from_db(user_id)


βœ… Very Fast (Remembers previous results):

from functools import lru_cache


@lru_cache(maxsize=128)
def get_user_data(user_id):
# Only runs ONCE per unique user_id
return fetch_from_db(user_id)



πŸ”Ή Use It to:

βœ”οΈ Speedup repetitive API calls, math calculations, or DB queries.
βœ”οΈ No third-party libraries needed (built into Python's standard library).
βœ”οΈ Prevent unnecessary server load.
❀1πŸ‘1