0% found this document useful (0 votes)
20 views33 pages

Advanced Python Data Structures & Functions

The document outlines the first lesson of an Advanced Python course, covering foundational concepts, data structures, and functions. It emphasizes writing idiomatic Python code and understanding advanced data structures, along with practical applications of Python in various fields. Key topics include variable references, mutable vs. immutable types, essential data structures, function definitions, and control flow statements.

Uploaded by

1qw2erty1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views33 pages

Advanced Python Data Structures & Functions

The document outlines the first lesson of an Advanced Python course, covering foundational concepts, data structures, and functions. It emphasizes writing idiomatic Python code and understanding advanced data structures, along with practical applications of Python in various fields. Key topics include variable references, mutable vs. immutable types, essential data structures, function definitions, and control flow statements.

Uploaded by

1qw2erty1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Advanced Python: Lesson 1

Foundations, Data Structures, and Functions

Farida Orucova

UFAZ Programming Club

October 18, 2025

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 1 / 28
Agenda

1 Course Introduction & Python Overview

2 Python in the Real World

3 Data Types & Variables Deep Dive

4 Container Methods in Action

5 Functions: Beyond the Basics

6 Loop Control: break, continue, pass

7 Summary & Practice

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 2 / 28
Welcome to Advanced Python

This isn’t a beginner’s course. We assume you know the basics.


Goal: To think like a Python developer.
Focus on:
Writing idiomatic (Pythonic) code.
Understanding advanced data structures and their trade-offs.
Mastering functions (OOP, decorators, generators come later).
Solving problems efficiently and clearly.

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 3 / 28
What Makes Python ”Pythonic”?

The Zen of Python (import this)


Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Readability counts.
...and more!
We will learn to write code that adheres to these principles.

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 4 / 28
The Zen of Python

[Link]

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 5 / 28
Where is Python Used?
Data Science & AI
Machine Learning: scikit-learn, Automation & Scripting
TensorFlow, PyTorch System Administration
Data Analysis: pandas, NumPy DevOps & CI/CD
Visualization: Matplotlib, File Processing
Seaborn, Plotly Web Scraping
Research & Prototyping
Other Major Areas
Web Development Scientific Computing
Backend: Django, Flask, Game Development (Pygame)
FastAPI Desktop GUI (Tkinter, PyQt)
REST APIs Networking & Security
Microservices Blockchain & Crypto
Content Management

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 6 / 28
Why Python Dominates These Fields

Rich Ecosystem: 300,000+ packages


on PyPI
Rapid Development: Write less code, Popular Companies
do more Google
Community Support: Huge, active Netflix
community Instagram
Cross-Platform: Runs everywhere Spotify
Integration: Works with other NASA
languages Dropbox
Readable Syntax: Easy to learn and Uber
maintain
Versatile: From scripts to large systems

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 7 / 28
Variables: Names and Objects

Key Concept: In Python, variables are references to objects.


Assignment is like adding a name tag
a = 10 # ’a’ is a name tag on the integer object ‘10‘
b = a # Now ’b’ is another name tag on the same object ‘10
a = 5 # ’a’ is moved to a new object ‘5‘. ’b’ still points
print(b) # Output: 10

This is crucial for understanding mutable vs. immutable types.

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 8 / 28
Core Data Types: Immutables
Immutable: Cannot be changed after creation.

int, float, str, bool, tuple


# Integers & Floats
x = 10
y = 3.14

# Strings Why Immutable?


name = "Alice" Safer (can’t be accidentally
# name[0] = ’E’ # ERROR! changed).
Can be used as dictionary keys.
# Booleans
Performance optimizations.
is_valid = True

# Tuples
coords = (4, 5)
# coords[0] = 1 # ERROR!
Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 9 / 28
Core Data Types: Mutables
Mutable: Can be changed after creation.

list, dict, set


# Lists
my_list = [1, 2, 3]
my_list[0] = 99 # OK
my_list.append(4) Why Mutable?
Efficient for dynamic data.
# Dictionaries Can be modified in-place.
person = {’name’: ’Bob’}
Caution: Be careful with
person[’age’] = 30 # OK
references!
# Sets
unique_nums = {1, 2, 2}
unique_nums.add(3) # OK

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 10 / 28
Tricky Question #1: Mutability

What is the output of this code?

list1 = [1, 2, 3]
list2 = list1
[Link](4)
print(list1)

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 11 / 28
Tricky Question #1: Mutability

What is the output of this code?

list1 = [1, 2, 3]
list2 = list1
[Link](4)
print(list1)

Answer
[1, 2, 3, 4]

Explanation: list1 and list2 are references to the same mutable list
object. Changing one affects the other.

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 11 / 28
Lists: Your Go-To Mutable Sequence

Essential List Methods


fruits = [’apple’, ’banana’]
[Link](’cherry’) # Add to end: [’apple’, ’banana’,
[Link](1, ’orange’) # Insert: [’apple’, ’orange’, ’ban
[Link](’banana’) # Remove first match: [’apple’, ’o
popped = [Link]() # Remove & return last item: ’cher
[Link]() # In-place sort: [’apple’, ’orange
[Link]() # In-place reverse: [’orange’, ’ap
new_list = [Link]() # Shallow copy (avoids reference i

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 12 / 28
Dictionaries: Key-Value Powerhouses
Essential Dictionary Methods
student = {’name’: ’Alice’, ’age’: 24, ’major’: ’CS’}

# Accessing
age = student[’age’] # Get value: 24
name = [Link](’name’) # Safer get: ’Alice’
email = [Link](’email’, ’N/A’) # Get with default: ’N/A’

# Modifying
student[’age’] = 25 # Update
student[’year’] = 3 # Add new key
popped = [Link](’major’) # Remove key & return value: ’CS

# Iterating
for key in student: # Or [Link]()
for value in [Link]():
for key, value in [Link]():
Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 13 / 28
Sets: Unordered and Unique

Essential Set Operations


setA = {1, 2, 3}
setB = {2, 3, 4}

[Link](4) # Add element: {1, 2, 3, 4}


[Link](1) # Remove, error if not present
[Link](10) # Remove, no error if not present

# Powerful Set Operations


union_set = setA | setB # OR: {1, 2, 3, 4}
intersection_set = setA & setB # AND: {2, 3}
difference_set = setA - setB # In A not B: {1}
sym_diff = setA ^ setB # XOR: {1, 4}

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 14 / 28
Tricky Question #2: Set Uniqueness

What will be the length of this set?

my_set = {1, 2, 2, [3, 4]}


print(len(my_set))

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 15 / 28
Tricky Question #2: Set Uniqueness

What will be the length of this set?

my_set = {1, 2, 2, [3, 4]}


print(len(my_set))

Answer
TypeError: unhashable type: ’list’

Explanation: Set elements must be immutable (hashable). A list is


mutable and cannot be placed inside a set. Tuples, however, can be.

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 15 / 28
Defining Functions: def

Syntax and Components


def function_name(parameter1, parameter2="default"):
"""
Docstring: Describes what the function does.
"""
# Function body
result = parameter1 + parameter2
return result # Returns None if omitted

Parameters vs. Arguments: Parameters are the names in the


definition. Arguments are the actual values passed.
Return: The return statement exits the function and passes back a
value. Without it, the function returns None.

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 16 / 28
Argument Types

Positional, Keyword, and Default


def describe_pet(pet_name, animal_type="dog", owner=None):
print(f"{owner}’s {animal_type} is named {pet_name}.")

# Positional arguments (order matters)


describe_pet(’Willie’, ’hamster’)

# Keyword arguments (order doesn’t matter)


describe_pet(animal_type=’cat’, pet_name=’Whiskers’)

# Mixing (positional first, then keyword)


describe_pet(’Fido’, owner=’Alice’) # Uses default for animal_

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 17 / 28
Tricky Question #3: The Mutable Default Argument
This is a classic Python pitfall. What’s wrong here?
def add_item(item, my_list=[]):
my_list.append(item)
return my_list

print(add_item(1)) # [1]
print(add_item(2)) # What will this output?

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 18 / 28
Tricky Question #3: The Mutable Default Argument
This is a classic Python pitfall. What’s wrong here?
def add_item(item, my_list=[]):
my_list.append(item)
return my_list

print(add_item(1)) # [1]
print(add_item(2)) # What will this output?

Answer
[1, 2]

Explanation: The default list is created only once when the function is
defined. Every subsequent call without a my list argument uses that
same list. The correct pattern is:

def add_item(item, my_list=None):


Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 18 / 28
Recursion: A Function Calling Itself
Base Case: The condition that stops the recursion.
Recursive Case: The part where the function calls itself with a
modified argument.

Factorial: n! = n * (n-1)!
def factorial(n):
# Base Case
if n == 0 or n == 1:
return 1
# Recursive Case
else:
return n * factorial(n - 1)

print(factorial(5)) # 5 * 4 * 3 * 2 * 1 = 120

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 19 / 28
break: Exit the Loop Immediately
Purpose: Completely terminate the loop when a condition is met.
Example: Find first even number
numbers = [1, 3, 5, 8, 9, 10, 12]

for num in numbers:


if num % 2 == 0:
print(f"Found first even number: {num}")
break # Exit loop immediately
print(f"Checking {num}")

print("Loop finished")

Output
Checking 1
Checking 3
Checking 5
Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 20 / 28
continue: Skip to Next Iteration
Purpose: Skip the rest of the current iteration and move to the next one.
Example: Process only odd numbers
numbers = [1, 2, 3, 4, 5, 6]

for num in numbers:


if num % 2 == 0:
continue # Skip even numbers
print(f"Processing odd number: {num}")
# More processing code here...

print("Loop finished")

Output
Processing odd number: 1
Processing odd number: 3
Processing odd number: 5
Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 21 / 28
pass: The Do-Nothing Statement
Purpose: A placeholder that does nothing. Used when syntax requires a
statement but you don’t want any action.
Common Use Cases
# 1. Placeholder for future code
def calculate_stats(data):
pass # TODO: Implement this later

# 2. Empty class or function


class MyClass:
pass # Minimal class definition

# 3. Empty loop or conditional


for i in range(10):
pass # Do nothing for each iteration

if condition:
pass # Handle this case later
Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 22 / 28
Tricky Question #4: break vs continue

What’s the difference in output between these two loops?

Loop A: Using break Loop B: Using continue


for i in range(5): for i in range(5):
if i == 3: if i == 3:
break continue
print(i) print(i)
print("Done") print("Done")

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 23 / 28
Tricky Question #4: break vs continue

What’s the difference in output between these two loops?

Loop A: Using break Loop B: Using continue


for i in range(5): for i in range(5):
if i == 3: if i == 3:
break continue
print(i) print(i)
print("Done") print("Done")

Answer
Loop A Output: 0 1 2 Done (breaks at 3)
Loop B Output: 0 1 2 4 Done (skips only 3)

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 23 / 28
Tricky Question #5: pass vs continue
When would you use pass instead of continue?
Scenario Analysis
# Option A: Using continue
for item in collection:
if not should_process(item):
continue
# 20 lines of complex processing...
process_item(item)

# Option B: Using pass


for item in collection:
if should_process(item):
# TODO: Implement processing logic
pass # Placeholder for future code
else:
log_skipped_item(item)
Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 24 / 28
Tricky Question #5: pass vs continue
When would you use pass instead of continue?
Scenario Analysis
# Option A: Using continue
for item in collection:
if not should_process(item):
continue
# 20 lines of complex processing...
process_item(item)

# Option B: Using pass


for item in collection:
if should_process(item):
# TODO: Implement processing logic
pass # Placeholder for future code
else:
log_skipped_item(item)
Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 24 / 28
Loop Control: Summary

When to use each:


break: ”I’m done with this entire loop now”
continue: ”I’m done with this iteration, move to the next one”
pass: ”I need a statement here syntactically, but I don’t want to do
anything”

Real-world analogy:
break: Leaving a party early because you’re tired
continue: Skipping one bad song but staying at the party
pass: Saving a seat for someone who hasn’t arrived yet

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 25 / 28
Key Takeaways

Python uses object references; understand mutable vs.


immutable.
Lists are versatile, dicts are fast for lookups, sets enforce uniqueness.
Functions are first-class objects. Beware of mutable default
arguments!
Recursion requires a clear base case.
Loop Control:
break: Exit loop entirely
continue: Skip to next iteration
pass: Placeholder that does nothing

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 26 / 28
Homework / Practice Problems

1 List Master: Write a function that takes a list and returns a new list
without duplicates. (Implement this both with and without using a
set).
2 Word Counter: Write a function that takes a string and returns a
dictionary where keys are words and values are the count of those
words. (Punctuation insensitive).
3 Recursive Fibonacci: Implement a function to find the n-th
Fibonacci number using recursion. Bonus: Why is this inefficient?
How could you improve it?
4 Loop Control Practice: Write a loop that processes numbers 1-20,
but:
Uses continue to skip multiples of 3
Uses break to stop if a number greater than 15 is prime
Uses pass as a placeholder for complex prime checking

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 27 / 28
Questions?

Farida Orucova (UFAZ Programming Club) Advanced Python: Lesson 1 October 18, 2025 28 / 28

You might also like