惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
T
Threatpost
WordPress大学
WordPress大学
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
PCI Perspectives
PCI Perspectives
T
The Exploit Database - CXSecurity.com
Y
Y Combinator Blog
雷峰网
雷峰网
爱范儿
爱范儿
The Hacker News
The Hacker News
Last Week in AI
Last Week in AI
Simon Willison's Weblog
Simon Willison's Weblog
T
Tor Project blog
S
Securelist
宝玉的分享
宝玉的分享
L
LangChain Blog
O
OpenAI News
AI
AI
P
Privacy International News Feed
L
LINUX DO - 最新话题
D
DataBreaches.Net
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Attack and Defense Labs
Attack and Defense Labs
罗磊的独立博客
M
MIT News - Artificial intelligence
Security Archives - TechRepublic
Security Archives - TechRepublic
月光博客
月光博客
博客园 - 【当耐特】
T
Tailwind CSS Blog
C
Cybersecurity and Infrastructure Security Agency CISA
H
Help Net Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
Jina AI
Jina AI
The Last Watchdog
The Last Watchdog
K
Kaspersky official blog
Webroot Blog
Webroot Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Blog — PlanetScale
Blog — PlanetScale
MyScale Blog
MyScale Blog
MongoDB | Blog
MongoDB | Blog
P
Proofpoint News Feed
Recorded Future
Recorded Future
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 三生石上(FineUI控件)
The Cloudflare Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Python for Beginners — Part 5: Collections
Ramesh S · 2026-06-23 · via DEV Community

Part 5 of a beginner-friendly series on learning Python from scratch.

In Part 4, we learned how to make decisions and repeat code with loops. Now we're going to upgrade that power dramatically: instead of working with single values, we'll work with entire collections of data.

This is where Python becomes truly versatile. Collections let you store multiple values in a single variable, organize data logically, and iterate over it with the loops you just learned. Most real programs spend their time managing collections.

Lists — Ordered, Changeable Collections

A list is a container that holds multiple values in a specific order. You can add, remove, or change items after creating the list.

Creating and accessing lists

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

Lists use square brackets and items are separated by commas. Items can be different types.

Access items by their index (position), just like strings:

fruits = ["apple", "banana", "cherry"]
print(fruits[0])    # apple
print(fruits[1])    # banana
print(fruits[-1])   # cherry (last item)

Get the length with len():

print(len(fruits))  # 3

Slicing lists

Just like strings, lists can be sliced:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[0:3])     # [1, 2, 3]
print(numbers[5:])      # [6, 7, 8, 9, 10]
print(numbers[::2])     # [1, 3, 5, 7, 9] (every 2nd item)

Essential list methods

Lists come with many built-in methods. Here are the most important:

fruits = ["apple", "banana"]

# Add items
fruits.append("cherry")              # Add to the end
fruits.insert(1, "mango")            # Insert at specific position
fruits.extend(["date", "elderberry"]) # Add multiple items

# Remove items
fruits.remove("banana")              # Remove by value
fruits.pop()                         # Remove last item and return it
fruits.pop(0)                        # Remove item at index 0
fruits.clear()                       # Remove all items

# Find and sort
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(numbers.count(1))              # 2 (how many 1's)
print(numbers.index(4))              # 2 (position of 4)
numbers.sort()                       # Sort in place: [1, 1, 2, 3, 4, 5, 6, 9]
numbers.reverse()                    # Reverse in place

# Create a copy
numbers_copy = numbers.copy()        # Independent copy

Important: sort() and reverse() change the list itself, not creating a new list. If you want to keep the original:

sorted_numbers = sorted(numbers)     # Returns a new sorted list

Modifying list items

Lists are mutable (changeable):

fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"              # Change the second item
print(fruits)                        # ["apple", "blueberry", "cherry"]

Iterating over lists

Combine lists with the for loops from Part 4:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

List comprehension — concise list creation

List comprehension is a compact way to create a new list by transforming or filtering an existing one:

# Create a list of squares
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)  # [1, 4, 9, 16, 25]

# Filter: only even numbers
evens = [x for x in numbers if x % 2 == 0]
print(evens)    # [2, 4]

# Transform and filter
result = [x * 2 for x in numbers if x > 2]
print(result)   # [6, 8, 10]

Read it as: "Create a list of [transformation] for [each item] in [source list] if [condition]"

List comprehensions are faster and more Pythonic than building lists with loops. They're common in real code.

Tuples — Ordered, Unchangeable Collections

A tuple is like a list, but immutable (unchangeable). Once created, you can't add, remove, or modify items.

Creating tuples

colors = ("red", "green", "blue")
single_item = ("hello",)  # Note the comma — without it, it's just a string
empty = ()

Use parentheses (round brackets). The comma is crucial for single-item tuples.

Accessing and iterating

colors = ("red", "green", "blue")
print(colors[0])      # red
print(colors[-1])     # blue
print(len(colors))    # 3

for color in colors:
    print(color)

Unpacking tuples

Tuples shine when you want to assign multiple values at once:

x, y = (1, 2)
print(x)  # 1
print(y)  # 2

# The parentheses are optional
name, age, city = "Ramesh", 25, "Chennai"
print(name, age, city)  # Ramesh 25 Chennai

# Swap variables easily
a, b = 1, 2
a, b = b, a  # Now a=2, b=1

Why use tuples?

  • Speed: Slightly faster than lists (minor difference)
  • Safety: Immutable, can't accidentally modify
  • Keys in dictionaries: Tuples can be dict keys; lists can't
  • Function returns: Functions often return tuples of multiple values
def get_user():
    return ("Ramesh", 25, "Chennai")

name, age, city = get_user()

Sets — Unique, Unordered Collections

A set is a collection of unique values with no specific order. Duplicates are automatically removed.

Creating sets

numbers = {1, 2, 3, 4, 5}
unique_letters = {"a", "b", "c", "a"}  # 'a' appears once
print(unique_letters)                   # {'a', 'b', 'c'} (order may vary)

empty_set = set()  # Note: {} creates an empty dict, not a set

Use curly braces. Sets have no indexing — you can't access the first item like you can with lists.

Common set operations

a = {1, 2, 3}
b = {3, 4, 5}

# Union — all items from both sets
print(a | b)        # {1, 2, 3, 4, 5}
print(a.union(b))   # {1, 2, 3, 4, 5}

# Intersection — items in both sets
print(a & b)        # {3}
print(a.intersection(b))  # {3}

# Difference — items in a but not b
print(a - b)        # {1, 2}
print(a.difference(b))    # {1, 2}

# Check membership
print(3 in a)       # True
print(4 in a)       # False

Set methods

numbers = {1, 2, 3}
numbers.add(4)          # Add one item
numbers.update([5, 6])  # Add multiple items
numbers.remove(2)       # Remove item (error if not found)
numbers.discard(10)     # Remove item (no error if not found)
numbers.clear()         # Remove all items

Use cases for sets

  • Remove duplicates: unique = set([1, 2, 2, 3, 3, 3]){1, 2, 3}
  • Check membership: Sets are faster than lists for in checks
  • Mathematical operations: Union, intersection, difference

Dictionaries — Key-Value Pairs

A dictionary stores pairs of keys and values. You access values using their keys, not positions.

Creating dictionaries

person = {
    "name": "Ramesh",
    "age": 25,
    "city": "Chennai"
}

scores = {"math": 95, "science": 87, "history": 92}
empty = {}

Use curly braces with key: value pairs. Keys are usually strings; values can be any type.

Accessing and modifying

person = {"name": "Ramesh", "age": 25}

print(person["name"])       # Ramesh
print(person["age"])        # 25

# Modify existing key
person["age"] = 26

# Add new key
person["city"] = "Chennai"

# Try to access non-existent key (safer way)
person.get("phone")         # None (no error)
person.get("phone", "N/A")  # N/A (default value)

Dictionary methods

person = {"name": "Ramesh", "age": 25, "city": "Chennai"}

# Get all keys, values, or pairs
print(person.keys())        # dict_keys(['name', 'age', 'city'])
print(person.values())      # dict_values(['Ramesh', 25, 'Chennai'])
print(person.items())       # dict_items([('name', 'Ramesh'), ('age', 25), ...])

# Iterate
for key in person:
    print(f"{key}: {person[key]}")

# Iterate over pairs
for key, value in person.items():
    print(f"{key}: {value}")

# Remove items
person.pop("age")           # Remove and return value
person.popitem()            # Remove last pair
person.clear()              # Remove all

# Update from another dict
person.update({"phone": "555-1234", "age": 26})

Nested dictionaries

Dictionaries can contain other dictionaries (or lists, or tuples):

team = {
    "player1": {"name": "Ramesh", "score": 95},
    "player2": {"name": "Priya", "score": 87},
    "player3": {"name": "Arun", "score": 92}
}

print(team["player1"]["name"])  # Ramesh
print(team["player2"]["score"]) # 87

Choosing the Right Collection

Collection Ordered Changeable Duplicates Use Case
List Store sequence of items
Tuple Immutable sequences, dict keys
Set Unique values, membership checks
Dict ✓ (Python 3.7+) ✓ (values) Store labeled data, key-value lookup

Practical Examples

Example 1: Managing a to-do list

todos = []

# Add tasks
todos.append("Buy groceries")
todos.append("Finish project")
todos.append("Call mom")

# Mark as done (remove)
todos.remove("Buy groceries")

# Show remaining
for i, task in enumerate(todos):
    print(f"{i+1}. {task}")

Output:

1. Finish project
2. Call mom

Example 2: Count word frequency

text = "the quick brown fox jumps over the lazy dog the fox"
words = text.split()
word_count = {}

for word in words:
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1

print(word_count)
# {'the': 3, 'quick': 1, 'brown': 1, 'fox': 2, ...}

Or more concisely:

from collections import Counter
word_count = Counter(words)
print(word_count)

Example 3: Find common interests

alice_interests = {"python", "music", "hiking", "gaming"}
bob_interests = {"python", "gaming", "cooking", "music"}

# What do they both enjoy?
common = alice_interests & bob_interests
print(common)  # {'python', 'gaming', 'music'}

# What does Alice enjoy that Bob doesn't?
alice_unique = alice_interests - bob_interests
print(alice_unique)  # {'hiking'}

Why This Matters

Collections are fundamental to every real program. You'll spend most of your programming time manipulating lists, dictionaries, and sets. Once you internalize which tool is right for each job, you'll write cleaner, faster code.

The most common beginner mistakes:

  • Confusing list and tuple syntax ([] vs ())
  • Trying to add items to a tuple (they're immutable!)
  • Using {} for an empty set and getting a dict instead
  • Trying to use lists as dictionary keys (they're unhashable)
  • Forgetting that dictionaries store by key, not position

This is Part 5 of an 8-part beginner Python series. Catch up on Part 1: Getting Started & Syntax, Part 2: Variables, Data Types & Numbers, Part 3: Strings & Booleans, and Part 4: Operators & Control Flow.