Day 12: Complete Guide to Lists in Python | Manipulating Data Collections Like Building Blocks

๐ŸŒŸ 1. Lists: The Universal Storage Box for Data

Programming Truth: Lists are the most widely used data structure in Python, capable of storing any type of data, like a mutable “magic array”! Life Scenario Analogy:

  • List โ†’ Train carriages (elements are passengers, who can get on and off at any time)

  • Index โ†’ Seat number (counting starts from 0)

  • Operations โ†’ Dispatcherโ€™s control panel (add, delete, modify, query)

๐Ÿ› ๏ธ 2. Creating Lists: Four Methods

1. Direct Creation Method

# Creating a list with different data typesfruits = ["apple", "banana", "orange"]          # String listscores = [90, 85, 77, 93]              # Integer listmixed = [1, "text", True, 3.14]         # Mixed type listempty = []                             # Empty list

2. Constructor Method

numbers = list(range(5))       # [0,1,2,3,4]chars = list("Python")         # ['P','y','t','h','o','n']

3. List Comprehension (Detailed Explanation Tomorrow)

squares = [x**2 for x in range(5)]  # [0,1,4,9,16]

๐Ÿ”„ 3. List Operations: The Four Kings of Add, Delete, Modify, Query

1. Add: Three Moves to Add Elements

animals = ["cat", "dog"]# Append elementanimals.append("rabbit")        # Add to the end โ†’ ["cat", "dog", "rabbit"]# Insert elementanimals.insert(1, "hamster")     # Insert at index 1 โ†’ ["cat", "hamster", "dog", "rabbit"]# Merge listsanimals.extend(["parrot", "goldfish"])  # โ†’ ["cat", "hamster", "dog", "rabbit", "parrot", "goldfish"]

2. Delete: Three Swords to Remove Elements

# Remove by valueanimals.remove("hamster")   # Remove the first matching item โ†’ ["cat", "dog", ...]# Remove by indexdel animals[0]          # Remove element at index 0 โ†’ ["dog", ...]popped = animals.pop(2) # Remove and return the element at index 2 ("rabbit")# Clear listanimals.clear()         # Clear โ†’ []

3. Modify: Element Transformation Technique

colors = ["red", "green", "blue"]colors[1] = "yellow"        # Modify index 1 โ†’ ["red", "yellow", "blue"]colors[::2] = ["pink", "purple"]  # Step modification โ†’ ["pink", "yellow", "purple"]

4. Query: Three Treasures to Locate Elements

nums = [10, 20, 30, 20]# Index queryprint(nums[0])          # 10 (first element)print(nums[-1])         # 20 (last element)# Slice queryprint(nums[1:3])        # [20, 30] (index 1 to 2)# Existence checkprint(30 in nums)       # Trueprint(nums.index(20))   # 1 (index of first occurrence)print(nums.count(20))   # 2 (number of occurrences)

โš ๏ธ 4. Beginner’s Pitfall Guide

Pitfall 1: Index Out of Bounds (IndexError)

lst = [1,2,3]print(lst[3])  # Error! Valid indices are 0-2

Pitfall 2: Modifying Immutable Elements

nested = [1, [2,3], 4]nested[1][0] = 5  # Correct โ†’ [1, [5,3], 4]nested[0] = [7,8] # Correct โ†’ [[7,8], [5,3], 4]

Pitfall 3: Shallow Copy Trap

a = [1,2]b = a       # Reference the same listb.append(3)print(a)    # [1,2,3] Synchronized modification!# Correct copyc = a.copy()    # Method 1d = a[:]        # Method 2

๐ŸŽฎ 5. Practical Application: Student Grade Management System

students = []while True:    print("\n1.Add 2.Delete 3.Modify 4.Query 0.Exit")    choice = input("Please choose:")        if choice == "1":        name = input("Name:")        score = float(input("Score:"))        students.append([name, score])            elif choice == "2":        name = input("Delete Name:")        for s in students:            if s[0] == name:                students.remove(s)                break                    elif choice == "3":        name = input("Modify Name:")        new_score = float(input("New Score:"))        for s in students:            if s[0] == name:                s[1] = new_score                    elif choice == "4":        print("\nCurrent Students:")        for idx, (name, score) in enumerate(students, 1):            print(f"{idx}. {name}๏ผš{score}")                elif choice == "0":        breakprint("System has exited")

โ“ 6. Soul-Searching Questions

Q1: How to traverse a list in reverse?

for item in reversed([1,2,3]):    print(item)  # 3 2 1

Q2: What is the difference between lists and tuples?โžค Lists are mutable, tuples are immutable! Tuples are defined with ()

Q3: How to randomly shuffle a list?

import randomnums = [1,2,3,4]random.shuffle(nums)  # e.g., [3,1,4,2]

Leave a Comment