1.6 Lists and List Comprehensions

Loading content...

1.6 Lists and List Comprehensions

Module 6 — Lists & List Comprehensions | Python for ML 🐍 Module 6 • Python for Machine Learning 📋 Lists & List Comprehensions Master Python's most powerful data structure — store, access, filter, and transform collections of data like a pro! 🚀 Imagine a shelf in a library 📚. Each slot on the shelf has a number (position) and holds one book. You can: 📖 Look at any book by its slot number ➕ Add new books to the end 🗑️ Remove a book from any slot 🔄 Rearrange books in order 📦 The shelf grows automatically as you add more! A Python list works exactly like this shelf. It's an ordered, mutable collection of items. 🎯 📖 Definition: A list is a built-in Python data structure that stores an ordered sequence of items. Items can be of any type, and you can add, remove, or change them anytime (lists are mutable). 👆 A list of scores with 5 slots (index 0 to 4). Like a numbered shelf! # Two ways to create a list scores = [85, 90, 72, 68, 95] # using [] empty = list() # using list() mixed = [1, "hello", 3.14, True] # any types! 💡 Key Point: Lists start counting at index 0, not 1! The first item is always at position 0. 📍 Q1: Python lists are immutable — you cannot change them after creation. 🤔 ○ False — lists are mutable ✏️ Ordered, mutable collection of items Position of an item (starts at 0) Extracting a portion of a list Remove and return item by index Can be changed after creation One-line way to create lists A list inside another list (2D) 🔢 Creating & Indexing Lists 📍 Indexing — Finding Items by Position Every item in a list has a position number (index). Think of it like seat numbers in a theater 🎭 — the first seat is #0! ➡️ Positive Indexing (left to right) fruits[0] → 🍎 (first) | fruits[4] → 🥝 (last) ⬅️ Negative Indexing (right to left) fruits[-1] → 🥝 (last) | fruits[-5] → 🍎 (first) fruits = ["apple", "banana", "cherry", "grape", "kiwi"] # Positive indexing (starts at 0) print(fruits[0]) # First item print(fruits[2]) # Third item # Negative indexing (starts at -1) print(fruits[-1]) # Last item print(fruits[-2]) # Second to last ['apple', 'blueberry', 'cherry', 'grape', 'kiwi'] 🔥 Pro Tip: Use [-1] to always get the last element, no matter how long the list is! Super useful in ML for getting the latest prediction. 🎯 Q2: Given colors = ["red", "green", "blue", "yellow"], what does colors[2] return? 🎨 Q3: To get the last item of any list, use the index ____ 🔚 🍕 Analogy: Cutting a Pizza Slicing is like cutting a portion from a pizza 🍕. You choose a start slice and an end slice, and Python gives you everything in between! 📖 Syntax: list[start:end:step] — Returns items from start up to (but NOT including) end, jumping by step. 🏃 nums = [10, 20, 30, 40, 50, 60, 70, 80] # idx: 0 1 2 3 4 5 6 7 print(nums[1:5]) # index 1 to 4 (not 5!) print(nums[:3]) # start to index 2 print(nums[5:]) # index 5 to end print(nums[::2]) # every 2nd item print(nums[::-1]) # reversed! [80, 70, 60, 50, 40, 30, 20, 10] 📐 Visual: How Slicing Works For nums[1:5] — the highlight covers index 1 through 4: 👆 Blue = included in slice. Index 5 is the stop — not included! ⛔ ⚠️ Common Trap: list[1:5] does NOT include index 5! Python slicing is start-inclusive, end-exclusive. Think of it as: "start ≤ index < end". 🚧 Q4: Given data = [10, 20, 30, 40, 50], what is data[1:4]? 🔍 Q5: Given x = [5, 10, 15, 20, 25, 30], how many items does x[::2] return? 🔢 🎬 Animation: The List Shelf See items slide into slots, get removed, sliced, and filtered ✨ 👆 Press Play to see how lists work step by step! 🧰 Analogy: A Toolbox for Your Shelf List methods are like tools — each one does a specific job on your list. 🛠️ Let's learn the most important ones! Remove first occurrence of x Remove & return item at i (default: last) Sort in ascending order (in-place) Reverse the list (in-place) Count how many times x appears cart = ["bread", "milk", "eggs"] print("After append:", cart) # 📍 Insert — add at specific position print("After insert(1):", cart) # 🗑️ Remove — removes first match print("After remove:", cart) # 📤 Pop — removes & returns by index print(f"Popped: {item}, Cart: {cart}")

Subject: Python for Machine Learning | Chapter: Chapter 1: Python Essentials

1.5 Functions and Return Values Chapter 1: Python Essentials 1.7 Dictionaries and Sets
Topics
Chapter 1: Python Essentials
Chapter 2: Python for Data Science
© Copyright © 2020 ALGOPK . All Rights Reserved.