Artificial Intelligence
🔰 Machine Learning & Artificial Intelligence Free Resources 🔰 Learn Data Science, Deep Learning, Python with Tensorflow, Keras & many more For Promotions: @love_data
Ko'proq ko'rsatish📈 Telegram kanali Artificial Intelligence analitikasi
Artificial Intelligence (@machinelearning_deeplearning) Ingliz til segmentidagi kanali faol ishtirokchi. Hozirda hamjamiyat 56 724 obunachidan iborat bo'lib, Taʼlim toifasida 3 072-o'rinni va Hindiston mintaqasida 5 900-o'rinni egallagan.
📊 Auditoriya ko‘rsatkichlari va dinamika
невідомо sanasidan buyon loyiha tez o‘sib, 56 724 obunachiga ega bo‘ldi.
14 Noyabr, 2026 dagi oxirgi ma’lumotlarga ko‘ra kanal barqaror faollikka ega. Oxirgi 30 kunda obunachilar soni 320 ga, so‘nggi 24 soatda esa 1 ga o‘zgardi va umumiy qamrov yuqori darajada qolmoqda.
- Tasdiqlash holati: Tasdiqlanmagan
- Jalb etish (ER): Auditoriya o‘rtacha 4.43% darajada jalb etiladi. Nashrdan keyingi dastlabki 24 soatda kontent odatda umumiy obunachilar sonining 1.31% ini tashkil etuvchi reaksiyalarni to‘playdi.
- Post qamrovi: Har bir post o‘rtacha 2 510 marta ko‘riladi; birinchi sutkada odatda 743 ta ko‘rish yig‘iladi.
- Reaksiyalar va o‘zaro ta’sir: Auditoriya faol: har bir postga o‘rtacha 13 ta reaksiya keladi.
- Tematik yo‘nalishlar: Kontent learning, classification, layer, pattern, chatbot kabi asosiy mavzularga jamlangan.
📝 Tavsif va kontent siyosati
Muallif resursni shaxsiy fikrni ifoda etish maydoni sifatida ta’riflaydi:
“🔰 Machine Learning & Artificial Intelligence Free Resources
🔰 Learn Data Science, Deep Learning, Python with Tensorflow, Keras & many more
For Promotions: @love_data”
Yuqori yangilanish chastotasi (oxirgi ma’lumot 16 Noyabr, 2026 da olingan) sababli kanal doimo dolzarb va katta qamrovli bo‘lib qoladi. Analitika auditoriya kontent bilan faol hamkorlik qilishini, uni Taʼlim toifasidagi muhim ta’sir nuqtasiga aylantirishini ko‘rsatadi.
scores = [0.2, 0.8, 0.6, 0.3]
high_scores = [
score for score in scores
if score >= 0.5
]
Output:
[0.8, 0.6]
⚠️ Common Mistakes
❌ Confusing order with if-else
# Wrong
[x for x in range(5) if x % 2 == 0 else 0]
# Correct
[x if x % 2 == 0 else 0 for x in range(5)]
❌ Making comprehensions unnecessarily complex
❌ Forgetting dictionary needs key: value
{x for x in range(5)} # This is a set
{x: x * x for x in range(5)} # This is a dict
💡 Key Takeaways
✅ List comprehension creates lists concisely
✅ Dictionary comprehension creates key-value pairs
✅ Both can include conditions
✅ if-else has a different syntax
✅ zip() is useful for combining multiple sequences
➡️ Double Tap ❤️ For More 🗂️
-----
1.28 ₽ · /balance_helpnumbers = []
for i in range(1, 6):
numbers.append(i)
print(numbers)
Output:
[1, 2, 3, 4, 5]
With list comprehension:
numbers = [i for i in range(1, 6)]
Much shorter.
Basic Syntax:
[expression for item in iterable]
Example:
squares = [x * x for x in range(1, 6)]
Output:
[1, 4, 9, 16, 25]
🔹 2. List Comprehension with Conditions
You can add an if condition:
even_numbers = [
x for x in range(1, 11)
if x % 2 == 0
]
Output:
[2, 4, 6, 8, 10]
General syntax:
[expression for item in iterable if condition]
🔹 3. Converting Values
Comprehensions aren't only for numbers.
names = ["alex", "sam", "john"]
uppercase = [name.upper() for name in names]
Output:
['ALEX', 'SAM', 'JOHN']
🔹 4. Using if-else
When using if-else, the syntax changes:
result = [
"Even" if x % 2 == 0 else "Odd"
for x in range(1, 6)
]
Output:
['Odd', 'Even', 'Odd', 'Even', 'Odd']
Remember:
# Only if
[expression for x in data if condition]
# if-else
[expression_if_true if condition else expression_if_false for x in data]
This is a common interview question.
🔹 5. Nested List Comprehension
Traditional approach:
result = []
for x in [1, 2]:
for y in [10, 20]:
result.append((x, y))
List comprehension:
result = [
(x, y)
for x in [1, 2]
for y in [10, 20]
]
Output:
[(1, 10), (1, 20), (2, 10), (2, 20)]
🔹 6. Dictionary Comprehension
Basic syntax:
{key: value for item in iterable}
Example:
squares = {
x: x * x
for x in range(1, 6)
}
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
🔹 7. Dictionary Comprehension with Conditions
even_squares = {
x: x * x
for x in range(1, 11)
if x % 2 == 0
}
Output:
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
🔹 8. Creating a Dictionary from Two Lists
names = ["Alex", "Sam", "John"]
scores = [85, 90, 78]
result = {
name: score
for name, score in zip(names, scores)
}
Output:
{'Alex': 85, 'Sam': 90, 'John': 78}
🔹 9. Transforming an Existing Dictionary
prices = {
"Laptop": 800,
"Phone": 500,
"Tablet": 300
}
updated_prices = {
item: price * 1.10
for item, price in prices.items()
}
🔹 10. Filtering a Dictionary
expensive = {
item: price
for item, price in prices.items()
if price > 500
}
Output:
{'Laptop': 800}squares = {x: x * x for x in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
even_squares = {
x: x * x
for x in range(1, 6)
if x % 2 == 0
}
# {2: 4, 4: 16}
🔹 13. Dictionary Keys Must Be Hashable
Dictionary keys must be hashable.
Valid examples:
data = {
"name": "Alex",
10: "ten",
(1, 2): "tuple"
}
❌ A list cannot be used as a key.
data = {
[1, 2]: "numbers"
} # TypeError
Because lists are mutable and therefore unhashable.
🔹 14. Can Dictionary Values Be Mutable?
Yes! Values can be almost any Python object.
data = {
"numbers": [1, 2, 3],
"info": {"age": 21}
}
So:
Keys → must be hashable
Values → can be mutable or immutable
🤖 Dictionaries in AI & Data Science
Dictionaries are everywhere in AI applications.
API responses
response = {
"status": "success",
"score": 0.94,
"model": "classifier"
}
Configuration
config = {
"learning_rate": 0.001,
"epochs": 10,
"batch_size": 32
}
Feature mapping
features = {
"age": 25,
"income": 60000,
"experience": 3
}
JSON data - JSON objects map naturally to Python dictionaries.
This makes dictionaries particularly important when working with REST APIs, machine learning pipelines, LLM APIs, and configuration files.
⚠️ Common Beginner Mistakes
❌ Mistake 1: Using an index
student[0]- Dictionaries are accessed using keys, not numerical indexes. ❌ Mistake 2: Assuming duplicate keys are preserved data = { "name": "Alex", "name": "Sam" } # {'name': 'Sam'} The final value wins. ❌ Mistake 3: Confusing keys and values
"name" in studentchecks whether "name" is a key. 💡 Key Takeaways ✅ Dictionaries store key-value pairs ✅ Keys must be unique ✅ Keys must be hashable ✅ Values can be of different data types ✅ Use [] for direct access ✅ Use .get() when a missing key should be handled safely ✅ .keys(), .values(), and .items() are important methods ✅ Dictionaries support nested structures and comprehensions ✅ They are heavily used in APIs, JSON, AI applications, and data processing 🔥 Mastering dictionaries is essential because you'll use them constantly when working with Python, APIs, data science, machine learning, and AI systems. Double Tap ❤️ For More
student = {
"name": "Alex",
"age": 21,
"course": "Python"
}
Here:
"name" → key
"Alex" → value
"age" → key
21 → value
🔹 1. Why Do We Need Dictionaries?
Suppose you have this list:
student = ["Alex", 21, "Python"]
You need to remember that:
Index 0 = name
Index 1 = age
Index 2 = course
That's not very readable.
With a dictionary:
student = {
"name": "Alex",
"age": 21,
"course": "Python"
}
print(student["name"])
Output:
Alex
🔹 2. Creating a Dictionary
Use curly braces {} with key-value pairs:
person = {
"name": "John",
"age": 25,
"city": "Delhi"
}
You can also create an empty dictionary:
data = {}
# Or
data = dict()
⚠️ Remember: {} creates an empty dictionary, not an empty set. For an empty set: set()
🔹 3. Dictionary Keys and Values
A dictionary contains: Key → Value
employee = {
"name": "Sam",
"salary": 50000,
"department": "IT"
}
Keys: name, salary, department
Values: Sam, 50000, IT
You can get them using:
employee.keys()
employee.values()
employee.items()
🔹 4. Accessing Dictionary Values
Using a key:
student = {
"name": "Alex",
"age": 21
}
print(student["name"]) # Alex
You can also use .get():
print(student.get("name")) # Alex
What is the difference?
If the key doesn't exist:
student["city"] ❌ Raises KeyError.
But:
student.get("city") ✅ Returns: None
You can also provide a default value:
student.get("city", "Unknown") # Output: Unknown
🔹 5. Adding New Items
Simply assign a value to a new key:
student = {
"name": "Alex",
"age": 21
}
student["city"] = "Delhi"
print(student)
# {'name': 'Alex', 'age': 21, 'city': 'Delhi'}
🔹 6. Updating Values
If the key already exists, assignment changes its value:
student["age"] = 22
You can also use .update():
student.update({
"age": 23,
"city": "Mumbai"
})
🔹 7. Removing Items
pop() - Removes a specific key and returns its value.
student.pop("age")
del removes a specific key:
del student["city"]
popitem() - Removes and returns the last inserted key-value pair.
student.popitem()
clear() - Removes everything:
student.clear()
🔹 8. Checking Whether a Key Exists
Use the in operator:
student = {
"name": "Alex",
"age": 21
}
print("name" in student) # Output: True
Important: "name" in student checks keys, not values.
🔹 9. Looping Through a Dictionary
Loop through keys:
for key in student:
print(key)
Loop through values:
for value in student.values():
print(value)
Loop through both:
for key, value in student.items():
print(key, value)
This is one of the most commonly used patterns when working with dictionaries.
🔹 10. Dictionary Length
Use len():
student = {
"name": "Alex",
"age": 21,
"course": "Python"
}
print(len(student))
# Output: 3
len() counts the number of key-value pairs.
🔹 11. Nested Dictionaries
A dictionary can contain another dictionary.
students = {
"student1": {
"name": "Alex",
"age": 21
},
"student2": {
"name": "Sam",
"age": 22
}
}
print(students["student1"]["name"]) # Output: Alex
Nested dictionaries are extremely common when working with structured data and APIs.
🔹 12. Dictionary Comprehensionsquares = {x: x * x for x in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
even_squares = {
x: x * x
for x in range(1, 6)
if x % 2 == 0
}
# {2: 4, 4: 16}
🔹 13. Dictionary Keys Must Be Hashable
Dictionary keys must be hashable.
Valid examples:
data = {
"name": "Alex",
10: "ten",
(1, 2): "tuple"
}
❌ A list cannot be used as a key.
Double Tap ❤️ For More{} when you want an empty Set.
❌ Trying to put a List inside a Set.
❌ Confusing remove() with discard().
Best Practices
✅ Use Sets when uniqueness matters.
✅ Use Sets for efficient membership checks.
✅ Use discard() when you want to safely remove a potentially missing element.
✅ Use Lists or Tuples when order and indexing are important.
Key Takeaways
• Sets store unique elements.
• Sets don't support indexing.
• Sets are mutable, but their individual elements must be hashable.
• add() adds one element, update() adds multiple.
• remove() raises an error if missing, discard() doesn't.
• Sets support Union, Intersection, Difference, and Symmetric Difference.
• Extremely useful for removing duplicates and membership checks.
➡️ Double Tap ❤️ For More 🗂️
-----
2.88 ₽ · /balance_help{1, 2, 3}
• This doesn't: {[1, 2], [3, 4]} — Lists are mutable
• This works: {(1, 2), (3, 4)} — Tuples with hashable elements
11. Sets in AI and Data Science
Sets are useful in many data-processing tasks.
categories = ["AI", "ML", "AI", "NLP", "ML"]
unique_categories = set(categories)
Sets can also be useful for:
• Removing duplicate records.
• Finding unique labels.
• Comparing datasets.
• Checking whether values exist.
• Finding common elements between datasets.
List vs Tuple vs Setimage_size = (1920, 1080)
The width and height form a fixed pair of values.
Tuples are also commonly used for coordinates:
point = (10, 25)
11. Tuples in AI and Data Science
Tuples appear frequently in Python-based AI applications.
For example, a dataset might contain:
sample = ("image_001.jpg", 1)
Here, the tuple can represent:
• File name
• Corresponding label
Tuples are also frequently encountered when working with functions that return multiple values, database results, coordinates, and fixed configurations.
⚠️ Important: Immutable Doesn't Always Mean Completely Unchangeable
A tuple itself is immutable, but it can contain mutable objects.
For example:
data = ([1, 2], [3, 4])
data[0].append(5)
print(data)
Output:
([1, 2, 5], [3, 4])
The tuple's elements cannot be replaced, but the list inside the tuple can still be modified.
This is an important distinction when working with nested data structures.
Common Beginner Mistakes
• ❌ Trying to modify a tuple element.
• ❌ Forgetting the comma when creating a single-element tuple.
• ❌ Assuming tuples are always faster or better than lists.
• ❌ Confusing tuple unpacking with indexing.
Best Practices
• ✅ Use tuples when the collection represents a fixed set of values.
• ✅ Use lists when the collection needs to change.
• ✅ Choose the data structure based on the behavior you need rather than simply assuming one is better.
Key Takeaways
• A tuple is an ordered, immutable collection.
• Tuples use parentheses by convention, such as (1, 2, 3).
• A single-element tuple requires a trailing comma: (10,).
• Tuples support indexing and slicing.
• Tuple unpacking makes it easy to assign elements to variables.
• Tuples have methods such as count() and index().
• A tuple can contain mutable objects, even though the tuple itself is immutable.
➡️ Double Tap ❤️ For More
-----
1.29 ₽ · /balance_help().
coordinates = (10, 20)
Another example:
student = ("Alice", 21, "Computer Science")
Parentheses Are Not Actually Required
Python identifies a tuple primarily by the commas.
numbers = 1, 2, 3
print(type(numbers))
Output:
<class 'tuple'>
2. Creating a Single-Element Tuple
This is a common beginner trap.
❌ This is not a tuple:
value = (10)
It's simply an integer.
To create a one-element tuple, you need a trailing comma:
value = (10,)
print(type(value))
Output:
<class 'tuple'>
3. Accessing Tuple Elements
Tuples support indexing just like lists.
colors = ("Red", "Green", "Blue")
print(colors[0])
print(colors[2])
Output:
Red
Blue
Python uses zero-based indexing.
4. Negative Indexing
You can access elements from the end.
colors = ("Red", "Green", "Blue")
print(colors[-1])
Output:
Blue
-1 refers to the last element.
5. Tuple Slicing
Tuples also support slicing.
numbers = (10, 20, 30, 40, 50)
print(numbers[1:4])
Output:
(20, 30, 40)
The ending index is excluded.
6. Tuples Are Immutable
Once a tuple is created, you cannot change an individual element.
❌ This produces an error:
numbers = (10, 20, 30)
numbers[0] = 100
Python raises a TypeError because tuples don't support item assignment.
If you need to modify the collection, you generally create a new tuple.
numbers = (10, 20, 30)
numbers = (100, 20, 30)
print(numbers)
Output:
(100, 20, 30)
7. Tuple Unpacking
Tuple unpacking allows you to assign tuple elements to multiple variables.
person = ("Alice", 25, "Engineer")
name, age, profession = person
print(name)
print(age)
print(profession)
Output:
Alice
25
Engineer
The number of variables normally needs to match the number of elements.
8. Using * in Unpacking
Python also allows extended unpacking.
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first)
print(middle)
print(last)
Output:
1
[2, 3, 4]
5
Notice that middle becomes a list, even though the original collection is a tuple.
9. Useful Tuple Methods
Tuples have fewer methods than lists because they are immutable.
count()
Counts how many times a value appears.word = "Python"
word[0] = "J"
Instead, you create a new string:
word = "Python"
word = "J" + word[1:]
print(word) # Jython
9. String Concatenation
You can combine strings using +.
first_name = "Alice"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name) # Alice Smith
10. f-Strings
f-strings provide a convenient way to insert variables into strings.
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message) # My name is Alice and I am 25 years old.
f-strings are widely used because they make formatted text easier to read.
11. Strings in AI and NLP
Strings become especially important when you move into Artificial Intelligence. AI systems frequently work with text such as: User questions, Chat messages, Documents, Reviews, Emails, Search queries, AI prompts.
Before text can be processed by many NLP and LLM systems, it often needs to be cleaned, transformed, tokenized, or converted into numerical representations.
For example:
text = " AI is AMAZING! "
cleaned_text = text.strip().lower()
print(cleaned_text) # ai is amazing!
This is a very simple example of text preprocessing.
Common Beginner Mistakes
❌ Forgetting that indexing starts at 0.
❌ Assuming the end index in slicing is included.
❌ Trying to modify an individual character.
❌ Confusing split() with join().
❌ Forgetting that spaces count toward string length.
Best Practices
✅ Use meaningful variable names.
✅ Use appropriate string methods instead of manually processing characters when possible.
✅ Use f-strings for readable string formatting.
✅ Remember that strings are immutable.
Key Takeaways
• A string is a sequence of characters.
• Python uses zero-based indexing.
• Negative indexing starts from -1.
• Slicing extracts portions of a string.
• len() returns the number of characters.
• Strings are immutable.
• Methods such as upper(), lower(), strip(), split(), and replace() are extremely useful.
• Strings are fundamental to NLP, LLMs, and AI applications.
➡️ Double Tap ❤️ For Morename = "Alice"
message = "Welcome to Python!"
Here, both "Alice" and "Welcome to Python!" are strings.
Why Do We Need Strings?
Strings are essential for:
• Storing text
• Processing user input
• Working with names and messages
• Reading and processing files
• Handling data from APIs
• Processing text for AI and NLP applications
1. Creating Strings
Strings can be created using single or double quotes.
name = "Alice"
city = 'Mumbai'
Both are valid.
You can also use triple quotes for multi-line strings:
message = """This is
a multi-line
string."""
2. Accessing Characters
Every character in a string has an index. Python uses zero-based indexing, meaning the first character is at index 0.
word = "Python"
print(word[0]) # P
print(word[1]) # y
print(word[5]) # n
The indexes look like this:
P y t h o n
0 1 2 3 4 5
3. Negative Indexing
Python also supports negative indexes. The last character has index -1.
word = "Python"
print(word[-1]) # n
print(word[-2]) # o
Indexing from the end looks like:
P y t h o n
-6 -5 -4 -3 -2 -1
4. String Slicing
Slicing allows you to extract part of a string.
Syntax: string[start:end] — The end index is not included.
Example:
word = "Python"
print(word[0:3]) # Pyt
Because indexes 0, 1, and 2 are included, but index 3 is excluded.
Slicing with a Step
word = "Python"
print(word[0:6:2]) # Pto
5. String Length
Use the len() function to find the number of characters.
text = "Python"
print(len(text)) # 6
Spaces are also counted as characters.
6. Important String Methods
upper() — Converts text to uppercase.
text = "hello"
print(text.upper()) # HELLO
lower() — Converts text to lowercase.
text = "HELLO"
print(text.lower()) # hello
strip() — Removes leading and trailing whitespace.
text = " Python "
print(text.strip()) # Python
replace() — Replaces part of a string.
text = "I like Java"
print(text.replace("Java", "Python")) # I like Python
split() — Splits a string into a list.
text = "Python is powerful"
words = text.split()
print(words) # ['Python', 'is', 'powerful']
join() — Combines elements into a string.
words = ["Python", "is", "powerful"]
text = " ".join(words)
print(text) # Python is powerful
7. Checking Content
You can check whether a substring exists using in.
text = "Python is easy"
print("Python" in text) # True
print("Java" not in text) # True
8. Strings Are Immutable
One of the most important things to understand about Python strings is that they are immutable. This means you cannot directly change an individual character.
❌ This is not allowed:map(), filter(), and sorted().
Now let's move to another important programming concept: Recursion.
📖 Phase 1: Programming Fundamentals
📌 Topic 13: Recursion
Recursion is a programming technique in which a function calls itself to solve a problem. Instead of solving the entire problem at once, recursion breaks the problem into smaller versions of the same problem.
🧠 Simple Example
Imagine you are standing in front of a staircase and want to reach the top.
Instead of thinking about the entire staircase, you can think:
👉 Reach the next step → repeat → repeat → reach the top.
That's similar to how recursion works.
1. Basic Recursive Function
Here's a simple example:
def countdown(n):
if n == 0:
return
print(n)
countdown(n - 1)
countdown(5)
Output:
5
4
3
2
1
Notice what happens:
countdown(5)
↓
countdown(4)
↓
countdown(3)
↓
countdown(2)
↓
countdown(1)
↓
countdown(0)
When n becomes 0, the function stops.
2. Base Case
Every properly designed recursive function needs a base case. The base case tells the function when to stop calling itself.
Example:
if n == 0:
return
Without a base case, the function may continue calling itself indefinitely.
❌ Example Without a Proper Base Case
def count(n):
print(n)
count(n - 1)
This function never reaches a stopping condition, eventually causing a RecursionError.
3. Recursive Case
The recursive case is where the function calls itself with a smaller or simpler version of the problem.
Example:
def countdown(n):
if n == 0:
return
print(n)
countdown(n - 1)
Here: countdown(n - 1) is the recursive case.
So a recursive function generally has:
Base Case → Stop
Recursive Case → Continue with a smaller problem
4. Factorial Using Recursion
Factorial is one of the most common examples of recursion.
Mathematically: 5! = 5 × 4 × 3 × 2 × 1
So: 5! = 120
We can define factorial recursively:
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Output: 120
Let's see how it works:
factorial(5)
= 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 5 × 4 × 3 × 2 × 1
= 120
5. Fibonacci Using Recursion
Another famous example is the Fibonacci sequence.
0, 1, 1, 2, 3, 5, 8, 13...
Each number is the sum of the previous two numbers.
A simple recursive implementation is:
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6))
Output: 8
Because: Fibonacci: 0, 1, 1, 2, 3, 5, 8
6. Recursion and the Call Stack
When a function calls itself, Python keeps track of each function call using the call stack.
For example: factorial(3) creates calls like:
factorial(3)
↓
factorial(2)
↓
factorial(1)
Once the base case is reached, the calls start returning in reverse order. This is why recursion can consume significant memory when there are many recursive calls.
7. Recursion vs Loops
Many problems can be solved using either recursion or loops.
Using a loop:
factorial = 1
for i in range(1, 6):
factorial *= i
print(factorial)
Using recursion:
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Both produce: 120
Which Should You Use?
Use a loop when:
✅ A simple repetition is enough.
Use recursion when:
✅ The problem naturally breaks into smaller versions of itself.
Recursion is particularly useful for problems involving:
Trees, Graph traversal, Divide-and-conquer algorithms, Backtracking, Searching hierarchical structures
8. Recursion in AI and Computer Sciencedef square(x):
return x * x
The same function using lambda:
square = lambda x: x * x
print(square(5))
Output: 25
Lambda Syntax
lambda arguments: expression
For example: lambda x: x + 10
• lambda → Keyword used to create the function
• x → Argument
• x + 10 → Expression that is returned
2. Lambda with Multiple Arguments
A lambda function can accept multiple arguments.
add = lambda a, b: a + b
print(add(10, 20))
Output: 30
multiply = lambda x, y: x * y
print(multiply(5, 4))
Output: 20
3. Lambda with if-else
Lambda functions can also contain conditional expressions.
check = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check(10))
print(check(7))
Output:
Even Odd4. Lambda with map() map() applies a function to every item in an iterable.
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, numbers))
print(squares)
Output: [1, 4, 9, 16, 25]
5. Lambda with filter()
filter() selects elements based on a condition.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Output: [2, 4, 6]
6. Lambda with sorted()
Lambda functions are very useful when sorting complex data.
Example:
students = [
("Rahul", 80),
("Priya", 95),
("Amit", 70)
]
students.sort(key=lambda x: x[1])
print(students)
Output: [('Amit', 70), ('Rahul', 80), ('Priya', 95)]
Here, lambda x: x[1] tells Python to sort using the second element of each tuple.
Lambda vs Regular Function
• Regular function:
def square(x):
return x * x
• Lambda function:
square = lambda x: x * x
Both produce the same result.
When Should You Use Lambda?
Use lambda when:
✅ The function is very small
✅ The operation is simple
✅ You need the function temporarily
✅ You're working with map(), filter(), or sorted()
Avoid lambda when:
❌ The logic becomes complicated
❌ The function needs multiple statements
❌ A meaningful function name and documentation would improve readability
In those situations, a regular def function is usually better.
Real-World AI/Data Example
Lambda functions are commonly used while preprocessing data.
scores = [45, 67, 82, 91, 38]
updated_scores = list(map(lambda x: x / 100, scores))
print(updated_scores)
Output: [0.45, 0.67, 0.82, 0.91, 0.38]
This kind of transformation can be useful when preparing data before feeding it into a Machine Learning model.
Common Beginner Mistakes
❌ Trying to put complex logic into a lambda
❌ Forgetting that a lambda automatically returns its expression
❌ Confusing map() and filter()
Key Takeaways
• Lambda functions are small anonymous functions
• They are created using the lambda keyword
• They can accept multiple arguments
• They return the result of a single expression
• They're especially useful with map(), filter(), and sorted()
• For complex logic, prefer a regular def function
➡️ Double Tap ❤️ For Morelambda keyword. They can take any number of arguments but only have one expression.
Example:
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
Lambda functions are often used for short operations where defining a full function would be unnecessary.
2. Higher-Order Functions
Higher-order functions are functions that can take other functions as arguments or return them as results.
Example:
def square(x):
return x * x
def apply_function(func, value):
return func(value)
result = apply_function(square, 5)
print(result) # Output: 25
In this example, apply_function takes another function as a parameter and applies it to the given value.
3. Map, Filter, and Reduce
These built-in functions allow you to apply operations on collections like lists.
• map() applies a function to all items in an iterable.
Example:
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, numbers))
print(squares) # Output: [1, 4, 9, 16]
• filter() filters items out of an iterable based on a condition.
Example:
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]
• reduce() (from the functools module) reduces an iterable to a single value using a binary function.
Example:
from functools import reduce
total = reduce(lambda x, y: x + y, numbers)
print(total) # Output: 10
4. Decorators
Decorators are a powerful way to modify the behavior of a function or class. They allow you to "wrap" another function to extend its behavior without permanently modifying it.
Example:
def decorator_function(original_function):
def wrapper_function():
print("Wrapper executed before {}".format(original_function.__name__))
return original_function()
return wrapper_function
@decorator_function
def display():
print("Display function executed")
display()
Output:
Wrapper executed before display Display function executedThe
@decorator_function syntax is a shorthand for applying the decorator.
5. Function Annotations
Python allows you to add annotations to function parameters and return values for better documentation.
Example:
def greet(name: str) -> str:
return f"Hello, {name}"
print(greet("Alice")) # Output: Hello, Alice
Annotations don't affect the program's execution but serve as hints for developers.
6. Recursive Functions
A recursive function is one that calls itself to solve a problem. It must have a base case to prevent infinite recursion.
Example:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
In this example, factorial calls itself until it reaches the base case of n == 0.
7. Scope of Variables
Understanding variable scope is crucial when working with functions.
• Local Scope: Variables defined inside a function are local to that function.
• Global Scope: Variables defined outside any function are global and can be accessed throughout the program.
Example:
x = "global"
def my_function():
global x
x = "local"
print("Inside function:", x)
my_function()
print("Outside function:", x)
Output:
Inside function: local Outside function: localHere, the
global keyword allows the function to modify the global variable x.
➡️ Double Tap ❤️ For Morefor i in range(5):
print(i)
Output:
0 1 2 3 4Notice that range(5) starts from 0 and stops before 5. Using range() You can specify a starting point and step.
for i in range(1, 11):
print(i)
Output:
1 2 3 4 5 6 7 8 9 10With a step:
for i in range(2, 11, 2):
print(i)
Output:
2 4 6 8 102. Looping Through a List You can directly iterate through a list.
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
print(fruit)
Output:
Apple Banana Mango3. while Loop A while loop executes as long as a condition remains True. Example:
count = 1
while count <= 5:
print(count)
count += 1
Output:
1 2 3 4 5Here, the loop continues until count <= 5 becomes False. ⚠️ Infinite Loops Be careful with while loops. This loop never stops:
count = 1
while count <= 5:
print(count)
Why?
Because count never changes, so the condition always remains True. Always make sure the condition can eventually become False.
4. break
break immediately stops the loop.
for i in range(1, 10):
if i == 5:
break
print(i)
Output:
1 2 3 45. continue continue skips the current iteration and moves to the next one.
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1 2 4 5The number 3 is skipped. 6. Nested Loops A loop can exist inside another loop.
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Nested loops are commonly used when working with grids, matrices, and combinations of data.
for vs while
Use a for loop when:
👉 You want to iterate through a sequence or range.
Use a while loop when:
👉 You want to continue running code until a condition changes.
Real-World AI Example
Loops are extremely common in AI and Data Science.
For example, you may need to process multiple files:
files = ["data1.csv", "data2.csv", "data3.csv"]
for file in files:
print("Processing:", file)
Output:
Processing: data1.csv Processing: data2.csv Processing: data3.csvThe same concept can be used when processing datasets, documents, images, API responses, or multiple AI model outputs. Common Beginner Mistakes ❌ Creating an infinite while loop. ❌ Forgetting to update the counter. ❌ Misunderstanding the stopping point of range(). ❌ Using break when you actually need continue. Key Takeaways • Loops allow you to repeat code efficiently. • for loops are commonly used for sequences and ranges. • while loops continue while a condition is True. • break stops a loop completely. • continue skips the current iteration. • Nested loops allow you to work with multiple levels of repetition. ➡️ Double Tap ❤️ For More
