Python for AI/ML - Day 3

Python for AI/ML - Day 3

Welcome to the 3rd day of Python session. The first two sessions can be reviewed in the link outlined below.

Day 1 - https://medium.com/unlearninglabs/ai-for-all-python-session-1-introduction-0fca3d927d6b

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:

  • Keys must be immutable (e.g., strings, numbers, or tuples containing immutable items).
  • Values can be of any data type (mutable or immutable).
  • Operations like lookups, insertions, and deletions are efficient.


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:

  • {"name": "Rahul", "age": 25, "city": "Mumbai"} creates a dictionary with three key-value pairs.
  • The dict() constructor is an alternative way to create dictionaries.
  • {} creates an empty dictionary.


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:

  • [] raises a KeyError if the key doesn’t exist.
  • .get() returns None (or a specified default value) if the key doesn’t exist.


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:

  • Adding a new key-value pair or updating an existing key’s value is done using the assignment operator =.


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:

  • del removes a key-value pair.
  • .pop() removes and returns the value for the specified key.
  • .popitem() removes and returns the last key-value pair.


Dictionary Methods

Here are some additional methods with examples:

  1. Keys, Values, and Items

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)]        

  1. Merging Dictionaries: update()

d1 = {"name": "Amit", "age": 25}
d2 = {"city": "Chennai", "age": 26}
d1.update(d2)
print(d1)  # Output: {'name': 'Amit', 'age': 26, 'city': 'Chennai'}        

  1. Copying a Dictionary: copy()

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'}        

  1. Clearing a Dictionary: clear()

data = {"name": "Raj", "age": 25}
data.clear()
print(data)  # Output: {}        

  1. Setting Default Values: setdefault()

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:

  • Creates a dictionary where keys are numbers, and values are their squares.


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:

  • def defines a function. The function is called using its name followed by parentheses.


Functions with Parameters

def add(a, b):
    return a + b

result = add(5, 10)
print(result)  # Output: 15        

Explanation:

  • add takes two arguments, a and b, and returns their sum.


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:

  1. Default parameters must come after all required parameters in the function definition.
  2. If a default parameter is specified, it can be overridden by passing a value during the function call.

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:

  • In greet, the name parameter has a default value of "Stranger".
  • In introduce, age defaults to 30 unless overridden.
  • In order, the quantity and price parameters both have default values, allowing for flexible function calls.


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:

  • apply_function takes a function func and a value value. It applies func to value and returns the result.
  • In this example, lambda x: x * 2 doubles the value of 5.


Recursive Functions

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # Output: 120        

Explanation:

  • A function that calls itself is called recursive. This example calculates the factorial of a number.
  • For factorial(5), the function computes 5 * factorial(4) and so on, until it reaches factorial(1).


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.


要查看或添加评论,请登录

Rajesh Pillai的更多文章

社区洞察

其他会员也浏览了