DEV Community

Ramesh S
Ramesh S

Posted on

Python for Beginners — Part 5: Collections

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]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Get the length with len():

print(len(fruits))  # 3
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Modifying list items

Lists are mutable (changeable):

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

Iterating over lists

Combine lists with the for loops from Part 4:

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

for fruit in fruits:
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

Output:

apple
banana
cherry
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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 = ()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 = {}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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})
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

Output:

1. Finish project
2. Call mom
Enter fullscreen mode Exit fullscreen mode

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, ...}
Enter fullscreen mode Exit fullscreen mode

Or more concisely:

from collections import Counter
word_count = Counter(words)
print(word_count)
Enter fullscreen mode Exit fullscreen mode

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'}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)