Python for AI/ML - Day 3
Rajesh Pillai
Co-Founder and CTO @Algorisys Technologies - Building Products and Upskilling upcoming generations
Welcome to the 3rd day of Python session. The first two sessions can be reviewed in the link outlined below.
Day 2 - https://medium.com/unlearninglabs/ai-for-all-python-session-2-conditionals-and-loops-0d7f4bcc9793
In this session we talk and discuss about dictionary and functions in general with some advanced examples.
Part 1: Python Dictionaries
A dictionary in Python is a collection of key-value pairs, where each key is unique and is used to access its corresponding value. Dictionaries are mutable and highly optimized for fast lookups due to their hash table implementation.
Key Features of Python Dictionaries:
Creating a Dictionary
# Using curly braces
example_dict = {"name": "Rohan", "age": 25, "city": "Mumbai"}
# Using the dict() constructor
example_dict2 = dict(name="Sneha", age=30, city="Delhi")
# Empty dictionary
empty_dict = {}
Explanation:
Accessing Values: [] vs .get()
data = {"name": "Ravi", "age": 25}
# Using []
print(data["name"]) # Output: Ravi
# Using .get()
print(data.get("age")) # Output: 25
print(data.get("city", "Not Found")) # Output: Not Found
Explanation:
Adding or Updating Items
data = {"name": "Priya", "age": 25}
data["city"] = "Pune" # Add new key-value pair
data["age"] = 26 # Update existing value
print(data) # Output: {'name': 'Priya', 'age': 26, 'city': 'Pune'}
Explanation:
Deleting Items: del, .pop(), .popitem()
data = {"name": "Kiran", "age": 25, "city": "Bangalore"}
# Using del
del data["age"]
print(data) # Output: {'name': 'Kiran', 'city': 'Bangalore'}
# Using .pop()
city = data.pop("city")
print(city) # Output: Bangalore
# Using .popitem()
last_item = data.popitem()
print(last_item) # Output: ('name', 'Kiran')
Explanation:
Dictionary Methods
Here are some additional methods with examples:
data = {"name": "Lakshmi", "age": 25}
print(list(data.keys())) # Output: ['name', 'age']
print(list(data.values())) # Output: ['Lakshmi', 25]
print(list(data.items())) # Output: [('name', 'Lakshmi'), ('age', 25)]
d1 = {"name": "Amit", "age": 25}
d2 = {"city": "Chennai", "age": 26}
d1.update(d2)
print(d1) # Output: {'name': 'Amit', 'age': 26, 'city': 'Chennai'}
d1 = {"name": "Sita", "age": 25}
d2 = d1.copy()
d2["age"] = 30
print(d1) # Output: {'name': 'Sita', 'age': 25'}
print(d2) # Output: {'name': 'Sita', 'age': 30'}
data = {"name": "Raj", "age": 25}
data.clear()
print(data) # Output: {}
data = {"name": "Meena"}
data.setdefault("age", 25)
print(data) # Output: {'name': 'Meena', 'age': 25}
Dictionary Comprehension
squares = {x: x**2 for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Explanation:
领英推荐
Part 2: Python Functions
A function is a block of reusable code that performs a specific task. Functions improve code modularity and reusability.
Defining and Calling Functions
def greet():
print("Hello, welcome to Day 3 of Python!")
greet() # Output: Hello, welcome to Day 3 of Python!
Explanation:
Functions with Parameters
def add(a, b):
return a + b
result = add(5, 10)
print(result) # Output: 15
Explanation:
Functions with Default Parameters
Default parameters allow you to specify default values for one or more parameters in a function. These values are used if no corresponding argument is provided during the function call.
Rules for Default Parameters:
Examples:
# Example 1: Default Parameter
def greet(name="Stranger"):
print(f"Hello, {name}!")
greet() # Output: Hello, Stranger!
greet("Priya") # Output: Hello, Priya!
# Example 2: Multiple Parameters with Defaults
def introduce(name, age=30):
print(f"My name is {name} and I am {age} years old.")
introduce("Ramesh") # Output: My name is Ramesh and I am 30 years old.
introduce("Geeta", 25) # Output: My name is Geeta and I am 25 years old.
# Example 3: Mixing Required and Default Parameters
def order(item, quantity=1, price=100):
total = quantity * price
print(f"You ordered {quantity} {item}(s) for a total of ?{total}.")
order("chai") # Output: You ordered 1 chai(s) for a total of ?100.
order("samosa", 3, 15) # Output: You ordered 3 samosa(s) for a total of ?45.
Explanation:
Lambda Functions
# Inline function
add = lambda a, b: a + b
print(add(5, 7)) # Output: 12
Importance of Lambda Functions
Lambda functions are particularly useful for creating short, single-use functions without the need to define a full function using def. They are often used in functional programming and data processing pipelines.
Custom Sorting:
# Custom Sorting with Lambda
items = [("laddu", 3), ("jalebi", 1), ("barfi", 2)]
sorted_items = sorted(items, key=lambda x: x[1])
print(sorted_items) # Output: [('jalebi', 1), ('barfi', 2), ('laddu', 3)]
Higher-Order Functions
A higher-order function is a function that accepts another function as an argument or returns a function as a result. This makes them useful for abstracting logic or reusing code efficiently.
# Passing functions as arguments
def apply_function(func, value):
return func(value)
result = apply_function(lambda x: x * 2, 5)
print(result) # Output: 10
Explanation:
Recursive Functions
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Explanation:
This summary encapsulates the fundamental concepts of Python dictionaries, functions, lambda expressions, and higher-order functions. Understanding these elements is crucial for effective programming in Python, enabling developers to write cleaner, more efficient, and more functional code.
NOTE: These articles are notes from the sessions. More in-depth technical explanations will be incrementally added.
Bench Sales Recruiter
1 个月[email protected]